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)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值