website content development template

2022.04.27

Foreword

(website content development template)When project development a few days ago,DiscoveryFlaskWrite some lightweightWebThe program is still more appropriate。In factFlaskFamily,In order to be able to develop more convenientlyRestfulStyle interface,Flask-restfulIs a good choice。AlthoughFlask-restfulProvide a relatively complete official documentation,But it is not very convenient to develop and go online projects,So I wrote oneFlask-restfulFast template。

This project adoptsMysqlAs a long -lasting database,A resource5Individual interface,SatisfiedwebDevelopment demand。

project address

First give the project address:Flask-restful-quick-start

website content development template

image-20211113211211982.png

Project Description

The first is the file structure of the project。

├── flask_app
│   ├── common
│   │   ├── __init__.py
│   │   └── utils.py
│   ├── user
│   │   ├── __init__.py
│   │   ├── models.py
│   │   └── views.py
│   └── __init__.py
├── config.py
├── LICENSE
├── main.py
└── requirements.txt

The blueprint is used in the project to divide the function block,Convenient to divide project modules,And improving maintenance。

At present, I think this is a relatively scientific file organization solution。

RestfulInterface design

Basic interfaces receive from two routes

======================================
Method of requesting        routing              Request content
POST        /userList           userInfo
GET         /userList           None
GET         /user               userId
PUT         /user               userInfo
DELETE      /user               userId
======================================

(website content development template)Making a simple introduction is to increase resources and query all resources from the resource list interface。

Other areas parameter requests and modifications、Delete and wait for a special resource interface。

This can be avoidedGETThe request with the problem with parameters and no parameters。

Unified treatment in the project can improve reliability,Reduce coding errors,I have unified two points here。

1、SqlalchemyofModelLayer object anddictConversion between。

def row2dict(row):
    """
    Reference documentation https://stackoverflow.com/questions/1958219/convert-sqlalchemy-row-object-to-python-dict
    WillmodelConvertdict
    :param row: Sqlalchemy model
    :return: Output dictionary
    """
    out_dict = {}
    for column in row.__table__.columns:
        out_dict[column.name] = str(getattr(row, column.name))
    return out_dict

(website content development template)You can easily use the above code to easilymodelConvertdictThe dictionary。

(website content development template)2、Unified recovery content

class BaseResponse:
    def __init__(self):
        self.result_code_success = 200
        self.result_code_fail = 201

    def success(self, msg="success", data={}):
        result = {
            "code": self.result_code_success,
            "message": msg,
            "data": data
        }
        return jsonify(result)

    def fail(self, msg="fail", data={}):
        result = {
            "code": self.result_code_fail,
            "message": msg,
            "data": data
        }
        return jsonify(result)

Unified recovery content includes“success”and“fail”Two situations,Can customize reply coding and content。

Startup project

Install

First clone project

$ git clone git@github.com:Jarrettluo/flask-restful-quick-start.git

cd flask-restful-quick-start

I suggest you use itideCreate a virtual environmentvenv,Avoid inconsistent packaging and system packs used by the project。

$ pip install requirements.txt

Last start project,Start development

(website content development template)$ python run main.py

Change setting

In the projectinit.pyThere are various parameters connecting the database,These are all defined settings。

user = "root"
password = "123456"
database = "flask_quick" # What needs to be modified
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql://%s:%s@localhost:3306/%s" % (user, password, database)

(website content development template)Use hereMysqlDB,Can be based on the actual situation,to modify。

At the same time, it is strongly recommended that you put these settings information onconfig.pyIn the file,This is convenient to modify。

In the main program,A method to prevent a database initialization,Can be cleared and created by the database。

def init_db():
    # Lost all tables
    db.drop_all()
    # Create all tables
    db.create_all()

Rapid development

Increasing the module only needs to be existinguserAfter the module is copied, modify it。

(website content development template)existflask_app.__init.pyRegister a blueprint

from flask_app.user import user_blueprint
app.register_blueprint(user_blueprint, url_prefix="/user")

existflask_app.user.__init.pyIncrease the blueprint

user_blueprint = Blueprint("user_blueprint", __name__, url_prefix="/user")
from flask_app.user import views

enjoy。

end

Guidance of pure new hands,For more content, please refer toFlask_restfulOfficial documentation.

If you think the above content is helpful to you, welcome to like you、Comment、Forward!
For more content, please check the author blog:https://jiaruiblog.com
orstarauthorgithub:
https://github.com/Jarrettluo?tab=repositories

返回列表
更多新闻资讯