如何使用Flask和SQLAlchemy将API请求存储在数据库中

时间:2019-04-25 21:29:12

标签: python flask flask-sqlalchemy

我正在尝试将API请求数据存储在数据库中。我正在从请求中查找某些字段,即URL,REMOTE_ADDR,以存储在数据库中。我正在使用flask和sqlalchemy进行api和与mysql数据库的数据库连接。任何帮助将不胜感激。

我创建了一个Log模型,将id,url,remote_addr字段存储在数据库中,并且我编写了一个函数来读取请求并将其映射到模型中。我不知道在尝试实现此目标时我不正确的地方。我包括我的app.py,log.py,loggerapi.py。

app.py

from flask import Flask, jsonify, send_from_directory
from flask_sqlalchemy import SQLAlchemy

from test import test_api
from usersapi import users_api
from authusersapi import authusers_api
from loggerapi import create_log
from database.db import db_uri

from flask_marshmallow import Marshmallow

import os

# Init app
app = Flask(__name__)

# config
app.config['SQLALCHEMY_DATABASE_URI'] = db_uri
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_ECHO'] = False

# Init db
db = SQLAlchemy(app)
db.create_all()

# Init ma
ma = Marshmallow(app)

# add urls
app.register_blueprint(test_api, url_prefix='/test')
app.register_blueprint(users_api, url_prefix='/users')
app.register_blueprint(authusers_api, url_prefix='/auth_users')

# logging
@app.before_request
def log_requests():
    create_log()

# Run the server
if __name__=='__main__':
    app.run(debug=True)

@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(app.root_path, 'static'),
                               'favicon.ico')

Log.py(模型)

from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow

from datetime import datetime
import socket

db = SQLAlchemy()
ma = Marshmallow()

class Log(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    url = db.Column(db.String(100))
    remote_addr = db.Column(db.String(100))
    created_at = db.Column(db.DateTime, default=datetime.utcnow) # the current timestamp

    def __init__(self, url, remote_addr):
        self.url = url
        self.remote_addr = remote_addr

class LogSchema(ma.Schema):
    class Meta:
        fields = ('url', 'remote_addr', 'created_at')

loggerapi.py(创建日志并将其提交到db的函数)

from flask import request

from database.db import session_scope

from Models.Log import Log, LogSchema

log_schema = LogSchema(strict=True)
logs_schema = LogSchema(many=True, strict=True)

def create_log():
    with session_scope() as session:
        url = request.url
        remote_addr = request.remote_addr

        new_log = Log(url, remote_addr)

        print(new_log)
        session.add(new_log)
        session.commit()

        return log_schema.jsonify(new_log)

实际结果:“日志”表中没有数据

预期结果:“日志”表中的数据

更新:

我发现我错过了使用flask的before_request功能的逻辑。我已经相应地更新了代码。谢谢鬣蜥。

1 个答案:

答案 0 :(得分:0)

将此块添加到app.py的代码中,以实际使用before_request。

@app.before_request
def log_requests():
    create_log()