flask web笔记

后端 flask

1.下载库

pip install flask

2.目录结构

  • 项目文件夹

    • media #放下载文件的文件夹

    • static #静态文件的文件夹

    • templates #视图文件的文件夹

    • util #工具类文件夹(非必要)

    • main.py #项目启动程序

3.主程序 main.py

# from flask import Flask, render_template, request, url_for, redirect, session
from flask import Flask
​
app = Flask(__name__)
@app.route('/')
def index():
    return 'flask web'
if __name__ == '__main__':
    app.run('127.0.0.1', 5000,debug=True)

启动直接和普通python文件启动方式一样,直接运行文件

然后访问127.0.0.1:5000

4.数据库

4.1.连接

import pymysql
app.config['SECRET_KEY'] = 'XXXXX'
conn = pymysql.connect(
    host='localhost',
    user='账号',
    password='密码',
    database='库名')
     """parms = {
        "host": "127.0.0.1",
        "user": "root",
        "password": "123456",
        "db": "chen",
        "charset": "utf8",
        "cursorclass": pymysql.cursors.DictCursor
    }"""

flask框架没有专门的数据库连接方式,一般都是借用其他第三方库例如:pymysql

4.2.操作

增删改

cursor = conn.cursor()
try:
#执行插入sql
    sql='sql语句{}'.format(x)
    #cursor.execute('sql语句%S,%s',(x,y))
    cursor.execute(sql)
    # 提交到数据库执行
    conn.commit()
except:
    # 如果发生错误则回滚
    conn.rollback()

cursor = conn.cursor()
sql='sql语句{}'.format(x)
cursor.execute(sql)
courses=cursor.fetchall()

5.创建视图文件

在文件夹templates中创建 index.html,代码如下:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>第一个网页</title>
    </head>
    <body>
        <a href="/get?name='cwm'">发送get请求</a>
        <form action="/post" method="post">
            <input type="text" name="name" value="cwq">
            <button type="submit">发送post请求</button>
        </form>
        <p>{{name}}</p>
    </body>
</html>

6.接收请求

6.1.GET请求

from flask import Flask, render_template, request, redirect
#@app.route('/get',methods=['GET']) 因为route是默认的get请求所以可以省略methods,如下
@app.route('/get') 
def r_get():
    c=request.args.get('name')
    return render_template('index.html',name=c)

6.2.POST请求

@app.route('/post',methods=['POST'])
def r_post():
    c=request.form.get('name')
    return render_template('index.html',name=c)

6.3.路径传参

@app.route('/url/<int:id>',methods=['GET','POST'])
def r_url(id):
    print(id)
    if request.method == 'GET':
        print('这是get请求')
        return render_template('index.html',x=id)
    else:
        print('这是post请求')
        return render_template('index.html',x=id)
  
  
'''
    "default": UnicodeConverter,
    "string": UnicodeConverter,
    "any": AnyConverter,
    "path": PathConverter,
    "int": IntegerConverter,
    "float": FloatConverter,
    "uuid": UUIDConverter,
​
'''