简体   繁体   English

烧瓶静态基本认证

[英]Flask-restful basic Authentication

I am new to Flask and I need some help for my school work. 我是Flask的新手,我的学校工作需要帮助。

I am trying to build a simple ToDo list system using flask-restful. 我正在尝试使用flask-restful构建一个简单的ToDo列表系统。

My current code looks like this: 我当前的代码如下所示:

class ToDoList(Resource):
    '''TODO LIST'''
    operation = ['delete']
    decorators = [auth.login_required, advertise('operation')]
    def post(self):
        """remove all item in the TODO list"""
        operation = request.args.get('op')
        if operation == 'delete':
            collection2.delete_many({})
            return {'Success': 'OK'}, 200
        return {'Error':'Illegal Operation'}, 400
    def get(self):
        """return a list of the TODO name"""
        list_1 = collection2.find()
        list_2 = []
        for each in list_1:
            list_2.append(JSONEncoder().encode(each))
        return {'list':list_2}, 200

It works, but I want only the post method to require authentication, and get method without authentication so anyone can acquire the list without login. 它的工作原理,但我只想要post方法需要进行身份验证,并get方法,无需认证,这样任何人都可以获取列表,而无需登录。 I am using the flask-restful I don't know how to give the decorators separately to each function. 我使用的是烧瓶式的,我不知道如何为每个功能分别分配装饰器。

I used flaskrestplus to do basic authentication. 我使用flaskrestplus进行基本身份验证。 All the required authorizations are provided as an authorizations dictionary. 所有必需的授权均作为授权字典提供。 Then they are passed to the API. 然后将它们传递给API。 Also the authorizations can be applied at the method level using 还可以使用以下方法在方法级别应用授权:

@api.doc(security='basicAuth')

The validation logic (can be ldap validation or db validation) can be writted in a decorator called requires_Auth. 验证逻辑(可以是ldap验证或db验证)可以写在名为require_Auth的装饰器中。 This decorator is invoked using 使用以下方法调用此装饰器

decorators = [requires_Auth]

Complete code 完整的代码

from flask import Flask, request
from flask_restplus import Api, Resource
from functools import wraps

def requires_Auth(f):
    @wraps(f)
    def decorator(*args, **kwargs):
        auth = request.authorization
        if auth:
           print "inside decorator", auth.username,auth.password
            return f(*args, **kwargs)
        else:
            return "Login required!!!!",401
    return decorator


authorizations = {
    'basicAuth': {
        'type': 'basic',
        'in': 'header',
        'name': 'Authorization'
    }
}
api = Api(app, version='1.0', 
    authorizations=authorizations
)

ns = api.namespace('/', description='Authentication API')

@ns.route('/withDecorator')
class HelloWorldWithDecorator(Resource):
    decorators = [requires_Auth]
    @api.doc(security='basicAuth')
    def get(self):        
        return {'hello': 'world'}

api.add_namespace(ns)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5001)

From Flask-RESTful documentation [ 1 ]: 从Flask-RESTful文档[ 1 ]:

Alternatively, you can specify a dictionary of iterables that map to HTTP methods and the decorators will only apply to matching requests. 另外,您可以指定一个可迭代的字典,该字典映射到HTTP方法,并且装饰器将仅应用于匹配的请求。

def cache(f):
    @wraps(f)
    def cacher(*args, **kwargs):
        # caching stuff
    return cacher

class MyResource(restful.Resource):
     method_decorators = {'get': [cache]}

     def get(self, *args, **kwargs):
        return something_interesting(*args, **kwargs)

     def post(self, *args, **kwargs):
        return create_something(*args, **kwargs)

In your case it would be: 您的情况是:

method_decorators = {'post': [auth.login_required]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM