2

Corniceを使用してRESTfulURLを作成します。

ピラミッドビーカーをインストール__init__.pyし、ドキュメントで指定されているようにインクルードを追加しました。

それでおしまい。それから私は私の見解でこれをしました:

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()

そしてこれが私の成果です

>>> 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

ご覧のとおり、新しいセッションが返されます。同じデータにアクセスできるように、同じセッションを取得するにはどうすればよいですか?

4

2 に答える 2

7

セッションは、クライアントに送信されたCookieを使用して追跡されます。したがって、「クライアント」(requestsライブラリ)は実際にそのCookieを再度送信する必要があります。

resp = requests.post('http://localhost/proj/1')
cookies = resp.cookies

requests.get('http://localhost/proj/2', cookies=cookies)

それでも、requests.Sessionセットアップを使用することをお勧めします。

with requests.Session() as s:
    s.post('http://localhost/proj/1')
    s.get('http://localhost/proj/2')
于 2012-08-27T23:00:31.460 に答える
3

@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
于 2012-08-27T23:24:34.910 に答える