Python Web开发初试,基于Flask

2023-04-27,,

目录
关于web框架
Python flask使用

关于web框架

仅仅对于应用层的coder而言,web框架的使用其实就是写路由,分发路由,写输出。当然如果要安全,要测试,要写优秀的接口,那需要继续积累经验和深入学习框架。

Python flask使用

写路由转发十分方便。

@app.route('/login', methods=['post'])
def login():
xxx
return xxx

python flask 提供蓝图机制实现路由分发,方便多文件模块化实现系统。

# navigate.py
from flask import Blueprint
navigate = Blueprint('navigate', __name__) @navigate.route('/')
def welcome():
return "wait"
# main.py
from nagivate import navigate
app.register_blueprint(navigate, url_prefix='/navigate')

前后端不分离可以直接用flask提供的render_template来渲染html后返回前端。

@app.route('/')
def welcome():
return render_template('welcome.html')

前后端分离,后端就是返回某种规定格式的数据(轻量化常用json),其中url、请求方法、请求内容、json格式、返回内容都是需要提前写接口文档的。

# app.py
import json from flask import Flask
from flask import render_template, request
app = Flask(__name__) @app.route('/')
def hello_world1(): # put application's code here
return render_template('index.html') @app.route('/data/modifyCertification', methods=['post'])
def hello_world(): # put application's code here
a = request.form.get('data1')
b = json.loads(a)
c = b['num1'] + b['num2']
return {
'success': '成功',
'data':{
'ret': c
}
}
if __name__ == '__main__':
app.run()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
//定义serializeObject方法,序列化表单 $.fn.serializeObject = function() { var o = {}; var a = this.serializeArray(); $.each(a, function() { if (o[this.name]) { if (!o[this.name].push) { o[this.name] = [ o[this.name] ]; } o[this.name].push(this.value || ''); } else { o[this.name] = this.value || ''; } }); return o; };
function f() {
let data1 = $('form').serializeObject(); //序列化表单数据
$.ajax({
type:'post',
dataType:'json',
url : '/data/modifyCertification',
data : {
"data1":JSON.stringify(data1)
},
success : function(res){
document.getElementById('out').innerHTML = res['success'] + '<br>' + res['data']['ret'];
},
error : function(){
document.getElementById('out').innerHTML = "失败";
}
});
}
</script>
</head>
<body>
<form>
<input type="number" name="num1"> num1 <br>
<input type="number" name="num2"> num2 <br>
<input type="button" onclick="f()" value="计算结果">
</form>
<div id="out"></div>
</body>
</html>

Python Web开发初试,基于Flask的相关教程结束。

《Python Web开发初试,基于Flask.doc》

下载本文的Word格式文档,以方便收藏与打印。