Pas*_*ten 7 python authentication python-asyncio aiohttp
我找不到aiohttp与登录页面结合的工作代码.目标很简单:使用用户名和密码进行基于表单的身份验证,我希望在随后的aiohttp async fetch调用中使用该cookie.
似乎整个Session概念在版本之间的aiohttp中发生了变化,所以我很好奇如何在最新版本中实现它.我不确定如何获取cookie一次,然后在异步事件中使用它.
我真的很想看到一个完整的例子,因为不幸的是我无法使用我在任何地方找到的片段.
我想这可能是一个开始,但我不确定,我当然不知道如何将所有内容连接到它(我还需要一个aiohttp.TCPConnector吗?)
http://aiohttp.readthedocs.org/en/latest/ client_reference.html#aiohttp.client.ClientSession
使用mechanize在Python 2中我的非异步版本的示例(虽然我自然地使用Python 3进行asyncio等):
import mechanize
import urllib
class MyClass()
def __init__(self):
self.data = {'username' : 'me', 'password' : 'pw'}
self.login_url = 'http://example.com/login'
self.login()
def call(self, url):
request2 = mechanize.Request(url)
self.cookie_jar.add_cookie_header(request2)
response2 = mechanize.urlopen(request2).read()
return response2
def login(self):
request = mechanize.Request(self.login_url)
# 'username' and 'password' keys are actually the name of the <input>
logInfo = urllib.urlencode({'username' : self.data['username'],
'password' : self.data['password']})
response = mechanize.urlopen(request, data = logInfo)
cookie_jar = mechanize.CookieJar()
cookie_jar.extract_cookies(response, request)
self.cookie_jar = cookie_jar
mc = MyClass()
mc.call('http://example.com/other_url')
Run Code Online (Sandbox Code Playgroud)
我刚刚添加了客户端基本身份验证的示例:client_auth.py
对你来说够了吗?
PS实际上ClientSession是旧式request+connector概念的替代。会话是保存会话相关信息的更自然的方式。但老方法仍然有效。
| 归档时间: |
|
| 查看次数: |
2687 次 |
| 最近记录: |