The basic usage flask_RESTful

Data Security

flask in the built-in functions can be implemented directly encryption and password verification

  • generate_password_hash
    • The same input, the output of each output ciphertext is different
  • check_password_hash
    • Call function can be password authentication directly

Realization of the principle

  • First password hash
  • Then hash stitching a random number
  • verification
    • Remove the random number
    • Password generation hash
    • Compare hash

Abnormal program

  • Abnormal production

    • raise
@property
def password(self):
    # 访问密码时抛出异常
    reise Exception("not be accessed")
  • assert

  • Handling Exceptions

    • try…except
  • Initiative Throws scene

    • The framework of their own package
    • Packaging tools for others to use

Flask-RESTful

,即给数据库中的字段定义映射,或叫设置别名# 添加参数的一般写法
parser = reqparse.RequestParser()  # 定义一个传入的参数
parser.add_argument("title", type=str, required=True, 
help="please add your title", action='append', dest='public_name', location=['form', 'values'])
# location中后面的参数先显示
  • Entry
    • reqparse.RequestParser()
      • Processing parameters
      • The parameter acquisition
      • Get check
        • parameter name
        • Type restriction type
          • Two type int and str
        • Error help
        • Is it necessary required
          • By default, arguments are not necessary, the parameters provided in the request does not belong to a part of the RequestParser words will be ignored. Set required=Trueto calladd_argument()
        • Privacy alias dest
          • Alias ​​set, the alias spread, the hidden field name in the database
        • Behind the first display parameter source location parameters
          • form
          • args
          • heads
          • cookies
          • values
          • json
        • Number of parameters, a plurality of parameter values ​​action
          • append additional parameters
          • store to store parameters
  • Output format conversion method
    • The object into JSON (dict)
    • marshal_with decoration
    • marshal function
      • First written template outgoing data
      • The data and template passed in

Template requires output

  • Dictionaries (dictionaries define a template, the output of the dictionary will be automatically converted to json data)
    • key is the key json
    • value isfileds.XXX
  • fields
    • attributeSpecify the mapping relationship
    • When formatting, default key according to the data dictionary lookup, specify the attribute=“xxx”following, will look for based on attribute. Fields can be achieved to the outgoing set the alias (xxx)
student_fields = {
	"name": fields.String(attribute=b_name)  # b_name是数据库中设置的字段名
}
  • default defaults
    • If there is no field or content, only to return null, may affect the function of front-end implementation, set the default value can solve this problem
student_fields = {
	"unknown": fields.String(default="")  # 设置默认值为空字符串
}
  • fields.Nested
    • Nested fields
    • Nested objects
    • And automatically handling individual objects list objects
student_fields = {  # 定义student输出数据的模板
	"name": fields.String(attribute=b_name)  # b_name是数据库中设置的字段名
}
retuen_fields = {
    "msg": fields.String,
    "status": fields.Integer,
    # 将student模板通过Nested方法传入到return模板中,
    # 将传入到data键的数据格式化,即下文中的"data": student
    "data": fields.Nested(student_fields)  
}

Introduced marshal_with()after the matshal_with()use of the method as a decorator, the output format

from flask_restful import Resource
class LearnResoure(Resource)
	@marshal_with(return_fields)
	def get(self):
        # 省略实现方法
        data = {  # 需要返回的数据
            "msg": "ok",
            "status": 200,
            "data": student,
        }
        return data
  • fields.List
    • List solve data type (old wording)

"data": fields.List(fields.Nested(student_fields))

fileds

  • Inherited from Raw
    • Attributes
      • default The default value of the property
      • attribute
    • method
      • The format of the incoming data format
      • First output call, the call data format when the output format
  • String
    • format
      • Convert str
      • text_type
  • Integer
    • format
      • int
  • Boolean

Packages

  • Method functions static methods will need to implement the function written inside, call the function to achieve functionality where needed, to achieve code reuse
  • Create a class inherits the parent class BaseResource, the class is defined in the parent class method inherited from his son in class, you can use this method, this approach may also be convenient to inherit the property of the parent class
  • Decorator, the same function is to create a method, but the method of its use as a decorative function to be achieved functionincoming decorators to add functionality to the method
# 定义一个装饰器
def login_required(fun):
    def wrapper(*args, **kwargs):
        # 省略需要给函数添加的功能
        return fun(*args, **kwargs)
    return wrapper
# 在实现的方法中添加装饰器的功能
@login_required
def post(self):
    # 处理传入的数据
    data = {
        "msg": "ok",
        "status": 200,
        "data": blog
    }
    return marshal(data, return_fields)

flask of

  • GET parameter acquisition mode
    • request.args
    • query_string
    • query_params
    • It can be used directly in all requests
    • Want to take this data can be written with a common request.args
  • POST parameters acquisition mode
    • request.form
    • POST, PATCH, PUT parameters are acquired using the form

Guess you like

Origin blog.csdn.net/qq_27114273/article/details/90715680