如何在web2py中进行需要登录的api调用? [英] How to make api call that requires login in web2py?

查看:37
本文介绍了如何在web2py中进行需要登录的api调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从应用程序访问 API.这些 API 有装饰器 @auth.requires_login().

I want to access APIs from application. Those APIs has decorator @auth.requires_login().

我正在使用

demo_app/controllers/plugin_task/task

url = request.env.http_origin + URL('api', 'bind_task')
page = urllib2.Request(url)
page.add_header('cookie', request.env.http_cookie)
response = urllib2.urlopen(page)

演示 API

api.py

@auth.requires_login()
@request.restful()
def bind_task():
    response.view = 'generic.json'
    return dict(GET=_bind_task)


def _bind_task(**get_params):
    return json.dumps({'status': '200'})

上面的代码给了我错误:HTTPError: HTTP Error 401: UNAUTHORIZED如何解决这个问题?我需要添加任何其他标题吗?

Above code gives me error : HTTPError: HTTP Error 401: UNAUTHORIZED How to solve this issue? I need to add any other headers?

目录结构-

Demo_app
|
|-controllers
   |
   |-api.py 
   |-plugin_task.py

控制器plugin_task.py调用api.py

应用程序 .w2p 文件 - 下载

Application .w2p file- Download

推荐答案

看来 这是在 Web2py 中指定 REST API 端点的正确方法:

It appears that this is the proper way to specify the REST API endpoint in Web2py:

auth.settings.allow_basic_login = True
@auth.requires_login()
@request.restful()
def api():
    response.view = 'generic.json'

    def GET(tablename, id):
        if not tablename == 'person':
            raise HTTP(400)
        return dict(person = db.person(id))

    def POST(tablename, **fields):
        if not tablename == 'person':
            raise HTTP(400)
        return db.person.validate_and_insert(**fields)

    return locals()

根据这个答案@auth.requires_login() 装饰器使用 HTTPBasicAuth,即易于使用 python -m pip install requests 之后:

According to this answer, that @auth.requires_login() decorator uses HTTPBasicAuth, which is easy to use after python -m pip install requests:

import requests


requests.get('http://127.0.0.1:8000/myapp/default/api/person/1.json', auth=('user', 'pass'))

这篇关于如何在web2py中进行需要登录的api调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆