You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
import json
from flask import Flask , jsonify
from flask_sqlalchemy import SQLAlchemy
# 创建Flask实例
app = Flask ( __name__ )
# 指定配置
# 指定数据库连接及表名
app . config [ ' SQLALCHEMY_DATABASE_URI ' ] = ' mysql+pymysql://root:4541@127.0.0.1:3306/diary_bottle?charset=utf8 '
# 省略提交操作
app . config [ ' SQLALCHEMY_COMMIT_ON_TEARDOWN ' ] = True
# 创建数据库对象
db = SQLAlchemy ( app )
class User ( db . Model ) :
"""
用户类
"""
__tablename__ = ' user '
id = db . Column ( db . String ( 12 ) , primary_key = True )
username = db . Column ( db . String ( 20 ) ) # 用户名
sex = db . Column ( db . String ( 2 ) ) # 性别
def user2dict ( user ) :
return {
' id ' : user . id ,
' username ' : user . username ,
' sex ' : user . sex
}
@app.route ( ' / ' )
def index ( ) :
return ' 服务器正常运行 '
# 设置路由
@app.route ( " /select " )
def select_user ( ) :
ulist = User . query . all ( )
# ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
# 考虑其它数据传递方法
ulist_json = [ ]
for u in ulist :
ulist_json . append ( ( json . dumps ( u , default = user2dict ) ) )
return jsonify ( ulist_json )
# ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
if __name__ == ' __main__ ' :
app . run ( )