我读到用cURL发送cookie有用,但不适合我。
我有一个这样的REST端点:
class LoginResource(restful.Resource):
def get(self):
print(session)
if 'USER_TOKEN' in session:
return 'OK'
return 'not authorized', 401
当我尝试访问端点时,它拒绝:
curl -v -b ~/Downloads/cookies.txt -c ~/Downloads/cookies.txt http://127.0.0.1:5000/
* About to connect() to 127.0.0.1 port 5000 (#0)
* Trying 127.0.0.1...
* connected
* Connected to 127.0.0.1 (127.0.0.1) port 5000 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.27.0
> Host: 127.0.0.1:5000
> Accept: */*
>
* HTTP 1.0, assume close after body
< HTTP/1.0 401 UNAUTHORIZED
< Content-Type: application/json
< Content-Length: 16
< Server: Werkzeug/0.8.3 Python/2.7.2
< Date: Sun, 14 Apr 2013 04:45:45 GMT
<
* Closing connection #0
"not authorized"%
我的~/Downloads/cookies.txt是:
cat ~/Downloads/cookies.txt
USER_TOKEN=in
服务器什么也收不到:
127.0.0.1 - - [13/Apr/2013 21:43:52] "GET / HTTP/1.1" 401 -
127.0.0.1 - - [13/Apr/2013 21:45:30] "GET / HTTP/1.1" 401 -
<SecureCookieSession {}>
<SecureCookieSession {}>
127.0.0.1 - - [13/Apr/2013 21:45:45] "GET / HTTP/1.1" 401 -
我错过了什么?
另一个使用json的解决方案。
旋度:
curl -c /tmp/cookie -X POST -d '{"chave":"email","valor":"hvescovi@hotmail.com"}' -H "Content-Type:application/json" localhost:5000/set
curl -b "/tmp/cookie" -d '{"chave":"email"}' -X GET -H "Content-Type:application/json" localhost:5000/get
curl -b "/tmp/cookie" -d '{"chave":"email"}' -X GET -H "Content-Type:application/json" localhost:5000/delete
PYTHON代码:
from flask import Flask, request, session, jsonify
from flask_session import Session
app = Flask(__name__)
app.secret_key = '$#EWFGHJUI*&DEGBHYJU&Y%T#RYJHG%##RU&U'
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
@app.route('/')
def padrao():
return 'backend server-side.'
@app.route('/set', methods=['POST'])
def set():
resposta = jsonify({"resultado": "ok", "detalhes": "ok"})
dados = request.get_json()
try:
if 'chave' not in dados: # não tem o atributo chave?
resposta = jsonify({"resultado": "erro",
"detalhes": "Atributo chave não encontrado"})
else:
session[dados['chave']] = dados['valor']
except Exception as e: # em caso de erro...
resposta = jsonify({"resultado": "erro", "detalhes": str(e)})
resposta.headers.add("Access-Control-Allow-Origin", "*")
return resposta
@app.route('/get')
def get():
try:
dados = request.get_json()
retorno = {'resultado': 'ok'}
retorno.update({'detalhes': session[dados['chave']]})
resposta = jsonify(retorno)
except Exception as e:
resposta = jsonify({"resultado": "erro", "detalhes": str(e)})
resposta.headers.add("Access-Control-Allow-Origin", "*")
return resposta
@app.route('/delete')
def delete():
try:
dados = request.get_json()
session.pop(dados['chave'], default=None)
resposta = jsonify({"resultado": "ok", "detalhes": "ok"})
except Exception as e: # em caso de erro...
resposta = jsonify({"resultado": "erro", "detalhes": str(e)})
resposta.headers.add("Access-Control-Allow-Origin", "*")
return resposta
app.run(debug=True)
另一个使用json的解决方案。
旋度:
curl -c /tmp/cookie -X POST -d '{"chave":"email","valor":"hvescovi@hotmail.com"}' -H "Content-Type:application/json" localhost:5000/set
curl -b "/tmp/cookie" -d '{"chave":"email"}' -X GET -H "Content-Type:application/json" localhost:5000/get
curl -b "/tmp/cookie" -d '{"chave":"email"}' -X GET -H "Content-Type:application/json" localhost:5000/delete
PYTHON代码:
from flask import Flask, request, session, jsonify
from flask_session import Session
app = Flask(__name__)
app.secret_key = '$#EWFGHJUI*&DEGBHYJU&Y%T#RYJHG%##RU&U'
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
@app.route('/')
def padrao():
return 'backend server-side.'
@app.route('/set', methods=['POST'])
def set():
resposta = jsonify({"resultado": "ok", "detalhes": "ok"})
dados = request.get_json()
try:
if 'chave' not in dados: # não tem o atributo chave?
resposta = jsonify({"resultado": "erro",
"detalhes": "Atributo chave não encontrado"})
else:
session[dados['chave']] = dados['valor']
except Exception as e: # em caso de erro...
resposta = jsonify({"resultado": "erro", "detalhes": str(e)})
resposta.headers.add("Access-Control-Allow-Origin", "*")
return resposta
@app.route('/get')
def get():
try:
dados = request.get_json()
retorno = {'resultado': 'ok'}
retorno.update({'detalhes': session[dados['chave']]})
resposta = jsonify(retorno)
except Exception as e:
resposta = jsonify({"resultado": "erro", "detalhes": str(e)})
resposta.headers.add("Access-Control-Allow-Origin", "*")
return resposta
@app.route('/delete')
def delete():
try:
dados = request.get_json()
session.pop(dados['chave'], default=None)
resposta = jsonify({"resultado": "ok", "detalhes": "ok"})
except Exception as e: # em caso de erro...
resposta = jsonify({"resultado": "erro", "detalhes": str(e)})
resposta.headers.add("Access-Control-Allow-Origin", "*")
return resposta
app.run(debug=True)