代码改变世界

Python - Flask框架

2022-04-07 10:52  起个昵称  阅读(74)  评论(0编辑  收藏  举报

根据flask文档 https://dormousehole.readthedocs.io/en/latest/tutorial/index.html

建立的一个demo系统

 

 启动flask服务命令

set FLASK_APP=flaskr
set FLASK_ENV=development
flask run

flask run启动后,只能本地的机子能访问。如果要让其他电脑也访问,需要 https://dormousehole.readthedocs.io/en/latest/deploying/index.html

 

 

然后在浏览器输入 http://127.0.0.1:5000/ 访问

 

flask学习笔记

 1 import hashlib
 2 from flask import Flask, request
 3 
 4 app = Flask(__name__)   # __name__ 当前模块名称
 5 
 6 @app.route('/')   # 绑定路径(默认根目录),默认get请求
 7 def hello():
 8     return 'Welcome to flask framework'
 9 
10 @app.route('/page1', methods=['get'])   # 指定地址和请求
11 def hello1():
12     return 'Welcome to flask framework get page'
13 
14 @app.route('/page2', methods=['post'])   # 不带参数的post请求
15 def hello2():
16     return 'Welcome to flask framework post page'
17 
18 @app.route('/page3', methods=['get'])   # 带参数的get请求
19 def hello3():
20     username = request.args.get('username')
21     password = request.args.get('password')
22     if username == 'admin' and password == 'admin':
23         return f'Welcome to flask framework {username}'
24     else:
25         return 'Incorrect username or password'
26 
27 @app.route('/page4', methods=['post'])   # 带参数的post请求
28 def hello4():
29     username = request.form.get('username')
30     password = request.form.get('password')
31     if username == 'admin' and password == 'admin':
32         return f'Welcome to flask framework {username}'
33     else:
34         return 'Incorrect username or password'
35 
36 def md5(args):
37     md5_value = hashlib.md5(str(args).encode('utf-8')).hexdigest()
38     return md5_value
39 
40 @app.route('/page5', methods=['post'])
41 def hello5():        # 参数加密,前段发送请求时也要加密
42     username = request.form.get('username')
43     password = request.form.get('password')
44     md5_user = md5('admin')
45     if username == md5_user and password == 'admin':
46         return f'hello 加密后的admin: {md5_user}'
47     else:
48         return 'Incorrect 加密后的 username or 未加密的 password'
49 
50 @app.route('/page6', methods=['get'])
51 def hello6():
52     header = request.headers.get('User-Agent')
53     if 'Mozilla' in header:
54         return f'已经带上请求头的请求{header}'
55     else:
56         return '请求失败,没有传入请求头'
57 
58 # 启动服务
59 if __name__ == '__main__':
60     app.run()