如何使用flask和sqlalchemy

时间:2016-07-19 22:19:40

标签: python rest flask sqlalchemy flask-sqlalchemy

好的我正在尝试使用基于Flask和sqlalchemy的restful API应用程序将新行插入到现有的mysql数据库表中。我希望它从传入的http POST请求中获取值,然后在" object"中创建一个新行。具有从POST请求接收的值的给定数据库的表。

注意:该应用程序通过带有httpd apache服务器的wsgi设置运行(cent os 6.6)

宁静的API部分按预期工作,但我似乎无法理解sqlalchemy部分。我需要为新手提供一些明确的具体建议。

下面的示例代码导致第30行读取错误(实际代码中的8实际上是8个参数,此示例代码中只有2个):

" TypeError: init ()只需1个参数(8个给定)"

不确定我做错了什么...抱歉代码很长,你必须滚动。

#! usr/bin/python
from flask import Flask, jsonify, request
from flask_restful import reqparse, abort, Resource, Api
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine, MetaData, Table, Column, Integer, Text, DateTime, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref, scoped_session, sessionmaker

app = Flask(__name__)
api = Api(app)

engine = create_engine('mysql+pymysql://user_name:password@1.1.1.1:3306/database', echo=True)
Base = declarative_base()
metadata = MetaData()
Base.metadata.reflect(engine)

class Object(Base):
    __table__ = Table('object', metadata, autoload = True, autoload_with=engine)

class submitObject(Resource):
    def post(self):

        request_data = request.get_json(force=True)

        r_object_id = request_data['object_id']
        r_object_name = request_data['object_name']

        r_object_json = jsonify(object_id=r_object_id, object_name=r_object_name)

        r_object_row = Object(r_object_id, r_object_name)

        db_session = scoped_session(sessionmaker(bind=engine))

        db_session.add(r_object_row)
        db_session.commit()
        db_session.remove()

        return r_ticket_json

api.add_resource(submitObject, '/object/submit')

if __name__ == "__main__":
    app.debug = True
    app.run()

非常感谢任何帮助!!

1 个答案:

答案 0 :(得分:1)

修复方法是改变实例化类的方式。

我改变了第30行:

import pickle
import base64
Obj = pickle.loads(base64.b64decode(token))

到此:

r_object_row = Object(r_object_id, r_object_name)