展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

Flask入门

pip install flask_sqlalchemy -i https://pypi.tuna.tsinghua.edu.cn/simple
  • 测试数据库连接
import pymysql
import pandas as pd
from sqlalchemy import create_engine
conn= create_engine("mysql+pymysql://root:123456@192.168.128.78:3306/test")
sql = f"""  select * from student """
original_df = pd.read_sql(sql, con=conn)
print( original_df[:10].values )
print(type (original_df[:10].values ))

exit()
  • config.py
HOSTNAME = '192.168.128.78'
PORT = '3306'
DATABASE = 'test'
USERNAME = 'root'
PASSWORD = '123456'
DB_URI = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8'.format(USERNAME,PASSWORD,HOSTNAME,PORT,DATABASE)
SQLALCHEMY_DATABASE_URI = f"mysql+pymysql://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DATABASE}?charset=utf8mb4"

SQLALCHEMY_ECHO = False
SQLALCHEMY_POOL_SIZE = 100
SQLALCHEMY_POOL_TIMEOUT = 60
SQLALCHEMY_MAX_OVERFLOW = 5
SQLALCHEMY_POOL_RECYCLE = 3600
SQLALCHEMY_POOL_PRE_PING = True
  • exts.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
  • models.py
from exts import db

class UserModel(db.Model):
    __tablename__ = "student"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(100), nullable=False)
    age = db.Column(db.String(200), nullable=False)

def model_to_dict(model):
    result = {}
    for column in model.__table__.columns:
        new_column_name=to_camel_case(column.name)
        result[new_column_name] = getattr(model, column.name)
    return result

def to_camel_case(word):
    parts = word.split('_')
    return parts
  • view.py
from flask import Blueprint

user = Blueprint('user',__name__,template_folder='user')

sessions={}
  • app.py
from flask import Flask, session, g
import config
from exts import db
from user.view import user
app = Flask(__name__)
app.config.from_object(config)
from flask import Flask, request, jsonify
db.init_app(app)
from models import UserModel ,model_to_dict

@app.route('/')
def hello_world():  # put application's code here
    return 'Hello World!'

@app.route('/getUser',methods=['POST','GET'])
def getUser():
    user_id = request.args.get("q")
    print( user_id)
    user = UserModel.query.get(user_id)
    return jsonify({"code": 200, "message": user.age })

if __name__ == '__main__':
    try:
        app.config['JSON_AS_ASCII'] = False
        app.register_blueprint(user)
        app.run(host="0.0.0.0", port=18888, debug=True)
    except Exception as e:
        print("An error occurred while running the application:", e)
  • 启动测试
posted @ 2023-12-06 14:50  DogLeftover  阅读(10)  评论(0编辑  收藏  举报