如何进行需要登录web2py的api调用? [英] How to make api call that requires login in web2py?
问题描述
我想从应用程序访问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错误401:未经授权
如何解决这个问题?我需要添加其他标题吗?
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
推荐答案
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安装请求后易于使用
:
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屋!