我需要将JSON从客户端POST到服务器.我正在使用Python 2.7.1和simplejson.客户端正在使用请求.服务器是CherryPy.我可以从服务器获取硬编码的JSON(代码未显示),但是当我尝试将JSON发送到服务器时,我得到"400 Bad Request".
这是我的客户端代码:
data = {'sender': 'Alice',
'receiver': 'Bob',
'message': 'We did it!'}
data_json = simplejson.dumps(data)
payload = {'json_payload': data_json}
r = requests.post("http://localhost:8080", data=payload)
Run Code Online (Sandbox Code Playgroud)
这是服务器代码.
class Root(object):
def __init__(self, content):
self.content = content
print self.content # this works
exposed = True
def GET(self):
cherrypy.response.headers['Content-Type'] = 'application/json'
return simplejson.dumps(self.content)
def POST(self):
self.content = simplejson.loads(cherrypy.request.body.read())
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
我正在执行一个使用Python请求库上传文件的简单任务.我搜索了Stack Overflow,似乎没有人遇到同样的问题,即服务器没有收到该文件:
import requests
url='http://nesssi.cacr.caltech.edu/cgi-bin/getmulticonedb_release2.cgi/post'
files={'files': open('file.txt','rb')}
values={'upload_file' : 'file.txt' , 'DB':'photcat' , 'OUT':'csv' , 'SHORT':'short'}
r=requests.post(url,files=files,data=values)
Run Code Online (Sandbox Code Playgroud)
我正在用我的文件名填充'upload_file'关键字的值,因为如果我把它留空,它会说
Error - You must select a file to upload!
Run Code Online (Sandbox Code Playgroud)
现在我明白了
File file.txt of size bytes is uploaded successfully!
Query service results: There were 0 lines.
Run Code Online (Sandbox Code Playgroud)
仅当文件为空时才会出现.所以我不知道如何成功发送我的文件.我知道该文件有效,因为如果我去这个网站并手动填写表格,它会返回一个很好的匹配对象列表,这就是我所追求的.我非常感谢所有提示.
其他一些线程相关(但没有回答我的问题):
我在烧瓶中设置了一个非常简单的邮政路线:
from flask import Flask, request
app = Flask(__name__)
@app.route('/post', methods=['POST'])
def post_route():
if request.method == 'POST':
data = request.get_json()
print('Data Received: "{data}"'.format(data=data))
return "Request Processed.\n"
app.run()
Run Code Online (Sandbox Code Playgroud)
这是我尝试从命令行发送的curl请求:
curl localhost:5000/post -d '{"foo": "bar"}'
Run Code Online (Sandbox Code Playgroud)
但仍然打印出"收到的数据:"无"".所以,它无法识别我传递的JSON.
在这种情况下是否有必要指定json格式?
我的login
终点看起来像
@app.route('/login/', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
print request.form # debug line, see data printed below
user = User.get(request.form['uuid'])
if user and hash_password(request.form['password']) == user._password:
login_user(user, remember=True) # change remember as preference
return redirect('/home/')
else:
return 'GET on login not supported'
Run Code Online (Sandbox Code Playgroud)
当我使用测试时curl
,GET
调用看起来像
? ~PYTHONPATH ? ? 43± ? curl http://127.0.0.1:5000/login/
GET on login not supported
Run Code Online (Sandbox Code Playgroud)
但是POST
,我无法访问表单数据并获取HTTP 400
? ~PYTHONPATH ? ? 43± ? curl -d "{'uuid': 'admin', 'password': …
Run Code Online (Sandbox Code Playgroud) 我无法读取通过XMLHttpRequest发布的烧瓶中的数据.我正在使用这个jquery插件裁剪图像并上传到服务器
data - 在使用XMLHttpRequest将图像发送到服务器之前,在json中收集和隐藏有关图像的信息
var formData = new FormData();
var name = "ex"; // Just an example
formData.append(name, JSON.stringify(data));
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.send(formData);
Run Code Online (Sandbox Code Playgroud)
在我的烧瓶代码中,我打印请求标题以查看内容类型
print(request.headers)
Run Code Online (Sandbox Code Playgroud)
我明白这一点
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,sv;q=0.6,fr;q=0.4
Host: localhost:5000
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary5e7lMMIQavXzSZg9
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36
Connection: keep-alive
Content-Length: 62714
Origin: http://localhost:5000
Pragma: no-cache
Cache-Control: no-cache
Cookie: session=eyJfZnJlc2giOmZhbHNlLCJjc3JmX3Rva2VuIjoiYTJhNTNlYzRkYjZlYzgzNzM2NDQ1ZjM5ZDAxNmY0MTlmY2RiZmRiOCIsInVzZXJuYW1lIjoidXNlcjEifQ.Cv2ADg.d8chDgzAA7fS2P9KcwzRINvLGOU
Referer: http://localhost:5000/loadProfile
Accept: */*
Run Code Online (Sandbox Code Playgroud)
我无法阅读内容
request.get_json()
如果我试试这个
print(request.get_json())
data = request.get_json()
print(data['name']) …
Run Code Online (Sandbox Code Playgroud) 使用flask构建应用程序。该应用程序使用表格结构来显示数据。其功能的一部分是从用户指定的表行中收集数据。为此,我在执行某些js的每一行上放置了一个按钮。js从该行收集信息,使用JSON.stringify()转换为json对象,并将发布请求发布到相关的烧瓶URL。
从js文件将jsonified对象的值记录到浏览器控制台中,表明其格式正确。发布请求联系正确的路由,但是request.get_json()函数在该路由的方法中返回值None。
我在烧瓶中设置了一条单独的路径进行测试。这是相关的代码
从javascript
function do_some_work(e) {
var row_data = get_table_row_data(e);
row_data = JSON.stringify(row_data);
console.log(row_data);
$.post("test", row_data);
}
Run Code Online (Sandbox Code Playgroud)
get_table_row_data()仅返回带有key:value对的对象。日志显示数据格式正确为json。
这是python代码
#TODO
@application.route('/test', methods=['GET', 'POST'])
def test():
data = request.get_json()
print("data is "+format(data))
return redirect(url_for('index'))
Run Code Online (Sandbox Code Playgroud)
这里的数据显示为None
任何帮助非常感谢
使用 Google 客户端库与视觉库交互。
我有一个从图像中检测标签的功能。
谷歌视觉.py
import os
from google.cloud import vision
from google.cloud.vision import types
from google.protobuf.json_format import MessageToJson
class GoogleVision():
def detectLabels(self, uri):
client = vision.ImageAnnotatorClient()
image = types.Image()
image.source.image_uri = uri
response = client.label_detection(image=image)
labels = response.label_annotations
return labels
Run Code Online (Sandbox Code Playgroud)
我有一个 api 来调用这个函数。
from flask_restful import Resource
from flask import request
from flask import json
from util.GoogleVision import GoogleVision
import os
class Vision(Resource):
def get(self):
return {"message": "API Working"}
def post(self):
googleVision = GoogleVision()
req = request.get_json()
url = …
Run Code Online (Sandbox Code Playgroud) 我正在创建一个使用在flask + python中编写的服务器的ios应用程序,当我与服务器建立连接以注册用户时,我一直在获取'NoneType'对象,这不是我的server.py文件中的可订阅错误.基本上我的问题是导致此错误的原因以及我如何解决此问题.此外,如果有人能指出我在不同或更简单的方式做正确的方向,我将不胜感激!
这是server.py文件:
import bcrypt
from flask import Flask, request, make_response,jsonify
from flask_restful import Resource, Api
from pymongo import MongoClient
from json import JSONEncoder
from bson.objectid import ObjectId
from functools import wraps
app = Flask(__name__)
mongo = MongoClient('localhost', 27017)
app.db = mongo.eventure_db
app.bcrypt_rounds = 12
api = Api(app)
# Authentication code.
def check_auth(username, password):
# check_auth should access the database and check if the username + password are correct.
# create a collection to hold the users.
user_collection = …
Run Code Online (Sandbox Code Playgroud) 客户代码:
import requests
import json
url = 'http://127.0.0.1:5050/login'
user = "newUser"
password = "password"
headers = {'content-type': 'application/json'}
response = requests.post(url, data={"user": user,"pass": password}, headers = headers)
Run Code Online (Sandbox Code Playgroud)
服务器代码:
from flask import Flask, request, make_response
app = Flask(__name__)
@app.route('/login', methods=['GET','POST'])
def login():
if request.method == 'POST':
username = request.form.get("user")
password = request.form.get("pass")
//more code
return make_response("",200)
if __name__ == "__main__":
app.run(host = "127.0.0.1", port = 5050)
Run Code Online (Sandbox Code Playgroud)
问题是我的用户名和密码始终为None.
我也试过用:
content = request.get_json(force = True)
password = content['pass']
Run Code Online (Sandbox Code Playgroud)
和
request.form['user']
Run Code Online (Sandbox Code Playgroud)
当我打印我的内容时:<请求' http://127.0.0.1:5050/login '[POST]>.因此我无法从客户端找到json发送. …
我有一些由前端在 JQuery 中生成的数组。
Edit1(基于 Edgar Henriquez 的回答):
my_jq.js:
var a = ['one','two'];
var b = ['three','four'];
var c = ['five'];
var d = ['six','seven','eight'];
var e = ['nine','ten','eleven'];
var newArray = [];
//jsonify to send to the server
$.ajax('/output', {
type: "POST",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(postData),
success: function(data, status){
console.log(newArray);
console.log(status);}
});
Run Code Online (Sandbox Code Playgroud)
我将选定的值传递给服务器(Flask/python)并让它计算笛卡尔积。然后我需要在 output.html 屏幕中显示输出
@app.route('/output', methods = ['GET','POST'])
def output():
data1 = request.get_json(force = True)
a = data1['a']
b = data1['b']
c = data1['c']
d = …
Run Code Online (Sandbox Code Playgroud) 我有一个带有此端点的Flask API:
@app.route('/classify/', methods=['POST'])
def classify():
data = request.get_json()
Run Code Online (Sandbox Code Playgroud)
当我使用python发布请求时,eveything很好.
但是当我使用Postman时,我得到:
<class 'werkzeug.exceptions.BadRequest'> : 400: Bad Request
Run Code Online (Sandbox Code Playgroud)
我同时发送相同的Json(我复制/粘贴它以确保).我是相当有信心的问题是由我的JSON一些"\ t"的,这是由蟒蛇,但不是邮差逃脱引起的.
有没有办法检索原始json,并在应用程序中处理它(逃避需要转义的东西)?还是另一种获得json的方式?
编辑:这是一个与你建议重复的问题不同的问题,因为你的建议使用get_json,这就是我的问题.
我正在尝试设置一个可以侦听和处理 POST 请求的小型 Python 3.8 脚本。我想监听来自 Trello 的 POST,然后记录数据。我读过的每个视频或指南都展示了如何处理来自 HTML 表单的 POST 请求。
特雷洛示例:
{
"action": {
"id":"51f9424bcd6e040f3c002412",
"idMemberCreator":"4fc78a59a885233f4b349bd9",
"data": {
"board": {
"name":"Trello Development",
"id":"4d5ea62fd76aa1136000000c"
},
"card": {
"idShort":1458,
"name":"Webhooks",
"id":"51a79e72dbb7e23c7c003778"
},
"voted":true
},
"type":"voteOnCard",
"date":"2013-07-31T16:58:51.949Z",
"memberCreator": {
"id":"4fc78a59a885233f4b349bd9",
"avatarHash":"2da34d23b5f1ac1a20e2a01157bfa9fe",
"fullName":"Doug Patti",
"initials":"DP",
"username":"doug"
}
},
"model": {
"id":"4d5ea62fd76aa1136000000c",
"name":"Trello Development",
"desc":"Trello board used by the Trello team to track work on Trello. How meta!\n\nThe development of the Trello API is being tracked at https://trello.com/api\n\nThe development of Trello Mobile …
Run Code Online (Sandbox Code Playgroud) 我正在尝试在 JavaScript 和 Python 之间进行数据通信,并且我是通过使用 JSON 变量来实现的,但是似乎每当我POST
从 JavaScript 发出请求时,request.get_json()
Python 接收器方法None
在我 print 时不会拾取任何内容并打印request.get_json()
。
Python 方法适用于将某些内容返回给 JS 的地方,但它始终是None
. 我的$.post()
方法有问题吗?
JavaScript$.post()
调用:
var items = {"robotCoor": {"robot_x": 1, "robot_y": 1},
"gridParams": {"goal_y": 0, "size_x": 16, "size_y": 16, "goal_x": 0},
"obsParams": {"obs_x3": 0, "obs_x4": 0, "obs_y4": 0, "obs_x2": 0, "obs_x1": 0, "obs_y1": 0, "obs_y2": 0, "obs_y3": 0},
"aiParams": {"layers": 0, "learning_rate": 0, "speed": 0}
};
var stuff = JSON.stringify(items);
console.log(stuff); #prints …
Run Code Online (Sandbox Code Playgroud) python ×12
flask ×9
json ×7
javascript ×2
ajax ×1
arrays ×1
cherrypy ×1
curl ×1
file ×1
file-upload ×1
flask-login ×1
http ×1
http-post ×1
jquery ×1
post ×1
python-3.8 ×1
python-3.x ×1
request ×1
rest ×1
windows ×1