[英]Pyramid returns new session
I use Cornice to make RESTful urls.我使用 Cornice 制作 RESTful 网址。
I installed pyramid-beaker and added the include to my __init__.py
as specified in the doc.我安装了金字塔烧杯并将包含添加到我的
__init__.py
如文档中所述。
That's it.而已。 Then I did this in my views:
然后我在我的观点中这样做了:
p_desc = """Service to post session. """
p = Service(name='p',\
path=root+'/1',\
description=register_desc)
g_desc = """Service to get session. """
g = Service(name='g',\
path=root+'/2',\
description=g_desc)
@g.get()
def view2(request):
print request.session
return Response()
@p.post()
def view1(request):
print 'here'
request.session['lol'] = 'what'
request.session.save()
print request.session
return Response()
And this is my outcome这是我的结果
>>> requests.post('http://localhost/proj/1')
<Response [200]>
>>> requests.get('http://localhost/proj/2')
<Response [200]>
Starting HTTP server on http://0.0.0.0:6543
here
{'_accessed_time': 1346107789.2590189, 'lol': 'what', '_creation_time': 1346107789.2590189}
localhost - - [27/Aug/2012 18:49:49] "POST /proj/1 HTTP/1.0" 200 0
{'_accessed_time': 1346107791.0883319, '_creation_time': 1346107791.0883319}
localhost - - [27/Aug/2012 18:49:51] "GET /proj/2 HTTP/1.0" 200 4
As you can see it gives back new session.如您所见,它返回新会话。 How do I get that same session so that I can access that same data?
我如何获得相同的会话以便我可以访问相同的数据?
Sessions are tracked with a cookie sent to the client.使用发送到客户端的 cookie 跟踪会话。 So your 'client' (the
requests
library) needs to actually send that cookie back again:因此,您的“客户端”(
requests
库)需要再次实际发送该 cookie:
resp = requests.post('http://localhost/proj/1')
cookies = resp.cookies
requests.get('http://localhost/proj/2', cookies=cookies)
Better still would be to use a requests.Session
set-up :更好的是使用
requests.Session
设置:
with requests.Session() as s:
s.post('http://localhost/proj/1')
s.get('http://localhost/proj/2')
To illustrate @Martijn Pieters's answer :为了说明@Martijn Pieters 的回答:
import requests
def t(r, url="http://httpbin.org/cookies"):
print(r.get(url).json['cookies'])
with requests.session() as s:
t(requests) # request without session
t(s) # request within session
t(s, "http://httpbin.org/cookies/set?name=value") # set cookie
t(requests) # request without session
t(s) # request within session
{} # request without session
{} # request within session
{u'name': u'value'} # set cookie
{} # request without session
{u'name': u'value'} # request within session
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.