Ubuntu16.04+pycharm+flask的表單提交及資料庫連線
實現目標:
#·1 表單提交 使用者名稱和登入名
#·2 然後跳轉到第二個頁面,展示磁碟檔案中的內容。
#·3 在第二個頁面上實現跳轉到第三個頁面按鈕
#·4 在第三個頁面上展示資料庫中的內容
環境配置:
1.安裝pycharm
2.安裝virtualenv
sudo apt-get install python-virtualenv
3.
$ mkdir myproject $ cd myproject
$ virtualenv venv
4.啟用虛擬環境:
. venv/bin/activate
5.在pycharm 中建立新工程,將工程路徑選擇到venv路徑下。
程式碼:
from flask import Flask, request, render_template, redirect
from wtforms import Form, TextField, PasswordField, validators
import pymysql
import sys
reload(sys)
sys.setdefaultencoding('utf8')
app = Flask(__name__)
class LoginForm(Form):
username = TextField("username", [validators.Required()])
password = PasswordField("password", [validators.Required()])
@app.route("/user", methods=['GET', 'POST'])
def login():
myForm = LoginForm(request.form)
if request.method == 'POST':
if myForm.username.data == "1" and myForm.password.data == "1" and myForm.validate():
return redirect("/news_view/")
else:
message = "Failed Login"
return render_template('index.html', message=message, form=myForm)
return render_template('index.html', form=myForm)
news_file = open("news.txt")
news = news_file.readlines()
@app.route("/news_view/")
def news_view():
return render_template('news_view.html', news=news)
conn = pymysql.connect(host='127.0.0.1', port=3306, user='man_user',
password='12345678', db='snailblog')
cursor = conn.cursor()
@app.route('/mysql_view/')
def mysql_view():
sql = "SELECT * FROM user"
cursor.execute(sql)
data = cursor.fetchall()
return render_template('mysql_view.html', data=data)
if __name__ == '__main__':
app.run(debug=True)