您的位置:首页 > 运维架构 > 网站架构

个人网站搭建(3)

2016-09-09 13:34 309 查看
连接数据库

首先安装mysql数据库。ubuntu可以使用命令:sudo apt-get install mysql-server安装。安装后运行:service mysqld start。

安装 Python-MySQLdb

命令:

#sudo apt-get install build-essential Python-dev libmysqlclient-dev

sudo apt-get install Python-MySQLdb


之后就是连接数据库了,当然连接数据库之前现在数据库中建立自己的数据表。


然后写一个连接数据库的.py文件:

#!/usr/bin/python
#coding:utf-8
import MySQLdb
conn = MySQLdb.connect(host="localhost", user="xxx", passwd="xxxxx",db="xx", port=3306, charset="utf8")
cur = conn.cursor()


xxx:mysql的用户名 xxxxx:mysql的密码

xx:自己建立数据表的名。

这样就可以建立起mysql的连接了。

然后前端可以通过js中的ajax发送数据,在index.py中接收到用户名和密码,然后判断用户名和密码即可做用户验证。

js代码:

$(document).ready(function(){
alert("good");
$("#login").click(function(){
var user = $("#username").val();
var pwd = $("#password").val();
var pd = {"username":user, "password":pwd};
$.ajax({
type:"post",
url:"/",
data:pd,
cache:false,
success:function(data){
alert(data);
},
error:function(){
alert("error!");
},
});

});
});


index.py代码:

#!/usr/bin/python
# coding=utf-8
import tornado.web
#import json
import methods.readdb as mrd
class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.render("index.html")

def post(self):
username = self.get_argument("username")
password = self.get_argument("password")
user_infos = mrd.select_table(table="users",column="*",condition="username",value=username)
if user_infos:
db_pwd = user_infos[0][2]
if db_pwd == password:
self.write("welcome you: " + username)
else:
self.write("your password was not right.")
else:
self.write("There is no thi user.")


效果图如下:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据库 ubuntu mysql