GVKun编程网logo

带有参数数据的Python请求发布(python 带参数)

24

这篇文章主要围绕带有参数数据的Python请求发布和python带参数展开,旨在为您提供一份详细的参考资料。我们将全面介绍带有参数数据的Python请求发布的优缺点,解答python带参数的相关问题,

这篇文章主要围绕带有参数数据的Python请求发布python 带参数展开,旨在为您提供一份详细的参考资料。我们将全面介绍带有参数数据的Python请求发布的优缺点,解答python 带参数的相关问题,同时也会为您带来asp.net – 使用IronPython调用带有参数的Python脚本 – “需要超过x值才能解压缩”、python-2.7 – 无法使用python和请求发布到solr服务器、Python带有参数的进程、python线程执行带有参数的任务的实用方法。

本文目录一览:

带有参数数据的Python请求发布(python 带参数)

带有参数数据的Python请求发布(python 带参数)

这是对API调用的原始请求:

POST http://192.168.3.45:8080/api/v2/event/log?sessionKey=b299d17b896417a7b18f46544d40adb734240cc2&format=json HTTP/1.1Accept-Encoding: gzip,deflateContent-Type: application/jsonContent-Length: 86Host: 192.168.3.45:8080Connection: Keep-AliveUser-Agent: Apache-HttpClient/4.1.1 (java 1.5){"eventType":"AAS_PORTAL_START","data":{"uid":"hfe3hf45huf33545","aid":"1","vid":"1"}}"""

该请求返回成功(2xx)响应。

现在,我尝试使用发送此请求requests

>>> import requests>>> headers = {''content-type'' : ''application/json''}>>> data ={"eventType":"AAS_PORTAL_START","data{"uid":"hfe3hf45huf33545","aid":"1","vid":"1"}}>>> url = "http://192.168.3.45:8080/api/v2/event/log?sessionKey=9ebbd0b25760557393a43064a92bae539d962103&format=xml&platformId=1">>> requests.post(url,params=data,headers=headers)<Response [400]>

一切对我来说看起来不错,我不太确定自己张贴的错误是什么导致400响应。

答案1

小编典典

params用于GET样式的URL参数,data用于POST样式的正文信息。在请求中 同时 提供 两种
类型的信息是完全合法的,您的请求也可以这样做,但是您已经将URL参数编码为URL。

您的原始帖子虽然包含 JSON 数据。requests可以为您处理JSON编码,并且也会设置正确的代码Content-Header;您需要做的就是将Python对象传递为json关键字JSON进行编码。

您也可以拆分URL参数:

params = {''sessionKey'': ''9ebbd0b25760557393a43064a92bae539d962103'', ''format'': ''xml'', ''platformId'': 1}

然后通过以下方式发布您的数据:

import requestsurl = ''http://192.168.3.45:8080/api/v2/event/log''data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}params = {''sessionKey'': ''9ebbd0b25760557393a43064a92bae539d962103'', ''format'': ''xml'', ''platformId'': 1}requests.post(url, params=params, json=data)

json关键字是新的requests2.4.2版本;
如果仍然需要使用旧版本,请使用json模块手动编码JSON,然后将编码后的结果作为data密钥发布;在这种情况下,您将必须显式设置Content-
Type标头:

import requestsimport jsonheaders = {''content-type'': ''application/json''}url = ''http://192.168.3.45:8080/api/v2/event/log''data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}params = {''sessionKey'': ''9ebbd0b25760557393a43064a92bae539d962103'', ''format'': ''xml'', ''platformId'': 1}requests.post(url, params=params, data=json.dumps(data), headers=headers)

asp.net – 使用IronPython调用带有参数的Python脚本 – “需要超过x值才能解压缩”

asp.net – 使用IronPython调用带有参数的Python脚本 – “需要超过x值才能解压缩”

我正在使用以下C#代码使用Iron Python调用 Python脚本:

ScriptEngine scriptEngine;

var opts = new Dictionary<string,object>();
opts["Arguments"] = new[] { 
    Server.MapPath(@"~\Processing\input.7z"),// Input
    Server.MapPath(@"~\Processing\key.pem"),// Key
    Server.MapPath(@"~\Processing\") };       // Output
        scriptEngine = Python.CreateEngine(opts);

var sp = scriptEngine.GetSearchPaths();
sp.Add(Server.MapPath(@"~\python\lib"));
scriptEngine.SetSearchPaths(sp);

var scope = scriptEngine.Runtime.ExecuteFile(Server.MapPath(@"~\python\test.py"));

该脚本采用以下参数:

arg0,input,key,output = sys.argv

我收到错误“需要超过3个值来解压”.我究竟做错了什么?

解决方法

这条线

arg0,output = sys.argv

将sys.argv中的参数列表解压缩到左侧的四个变量中.由于sys.argv中只有三个参数,因此失败并显示您发布的错误消息(显然您需要手动传入脚本路径,以使其显示为sys.argv中的第一个元素).

尝试使用不同的方式传递命令行参数(从this answer开始):

scriptEngine.Sys.argv = List.Make(new[] { 'input.7z',... });

或者,如果这不起作用,则从Python文件中的赋值中删除arg0变量,或者将脚本的路径显式添加为C#中的第一个参数.

python-2.7 – 无法使用python和请求发布到solr服务器

python-2.7 – 无法使用python和请求发布到solr服务器

这是我试图实现的代码: –

import requests
import tornado.ioloop
import tornado.web
import tornado.autoreload
import json

class MainHandler(tornado.web.RequestHandler):
        def get(self):
            payload = [{"id" : "978-0641723445","cat" : ["book","hardcover"],"name" : "The Lightning Thief","author" : "Rick Riordan","series_t" : "Percy Jackson  Olympians","sequence_i" : 1,"genre_s" : "fantasy","inStock" : True,"price" : 12.50,"pages_i" : 384}]
            url = ''http://localhost:8983/solr/update/json''
            headers = {''content-type'' : ''application/json''}
            # files = {''file'': (''books.json'',open(''books.json'',''rb''))}
            timeline = requests.post(url,data = json.dumps(payload),headers = headers)
            self.write(timeline.text)
class QueryHandler(tornado.web.RequestHandler):
        def get(self):
            # timeline = requests.get(''http://localhost:8983/solr/collection1/select?q=a&wt=json&indent=true'')
            payload = {''q'' : ''a'',''wt'' : ''json'',''indent'' : True}
            timeline = requests.get(''http://localhost:8983/solr/collection1/select'',params = payload)
            self.write(timeline.json())
application = tornado.web.Application([
    (r"/",MainHandler),(r"/query",QueryHandler)
])

if __name__ == "__main__":
    application.listen(8888)
    io_loop = tornado.ioloop.IOLoop.instance()
    tornado.autoreload.start(io_loop)
    io_loop.start()

我能够在localhost:8888 / query上查询solr服务器
但是在localhost:8888我试图发布数据,我从solr得到这个回复: –

{
responseHeader: {
status: 0,QTime: 46
}
}

数据未发布到solr服务器.

有什么建议 ??

解决方法

代码在标头中不包含commitWithin信息.参数以毫秒为单位.只有在提交后,才能从Solr搜索数据.以下可以作为将数据POST到solr的示例.将JSON标头与commitWithin时间以及数据作为JSON字符串添加到数据参数

requests.post(“http:// localhost:8983 / solr / collection1 / update?wt = json”,headers = {“Content-Type”:“application / json”},data =''{“add”:{“ doc“:{”id“:14,”log_type“:”debug“,”log_text“:”来自Kimy的调试事务“},”boost“:1.0,”overwrite“:true,”commitWithin“:1000} }“)

回应:

{ “responseHeader”:{ “状态”:0 “QTIME”:128}}

Python带有参数的进程

Python带有参数的进程

Python一般使用*arg表示不定长参数,**kwargs表示关键字参数也是不定长的

from multiprocessing import *


def print_info(name,age):
    print(f'{name}, {age}')

# args 元组传入 位置参数
# sub_process = Process(target=print_info, args=('Tom',18))

# kwargs 字典传入 关键字参数
# sub_process = Process(target=print_info, kwargs={'name':'Tom', 'age':18})

sub_process = Process(target=print_info,args=('Tom',),kwargs={'age':18})
if __name__ == '__main__':
    sub_process.start()

python线程执行带有参数的任务

python线程执行带有参数的任务

python线程执行带有参数的任务


1. 线程执行带有参数的任务的介绍

前面使用线程执行的任务是没有参数的,假如我们使用线程执行的任务带有参数,如何给函数传参呢?

Thread类执行任务并给任务传参数有两种方式:

  • args 表示以元组的方式给执行任务传参
  • kwargs 表示以字典方式给执行任务传参

2. args参数的使用

示例代码:

import threading
import time


# 带有参数的任务
def task(count):
    for i in range(count):
        print("任务执行中..")
        time.sleep(0.2)
    else:
        print("任务执行完成")


if __name__ == '__main__':
    # 创建子线程
    # args: 以元组的方式给任务传入参数
    sub_thread = threading.Thread(target=task, args=(5,))
    sub_thread.start()

执行结果:

3. kwargs参数的使用

示例代码:

import threading
import time


# 带有参数的任务
def task(count):
    for i in range(count):
        print("任务执行中..")
        time.sleep(0.2)
    else:
        print("任务执行完成")


if __name__ == '__main__':
    # 创建子线程
    # kwargs: 表示以字典方式传入参数
    sub_thread = threading.Thread(target=task, kwargs={"count": 3})
    sub_thread.start()

执行结果:

4. 小结

  • 线程执行任务并传参有两种方式:
    • 元组方式传参(args) :元组方式传参一定要和参数的顺序保持一致。
    • 字典方式传参(kwargs):字典方式传参字典中的key一定要和参数名保持一致。

今天关于带有参数数据的Python请求发布python 带参数的讲解已经结束,谢谢您的阅读,如果想了解更多关于asp.net – 使用IronPython调用带有参数的Python脚本 – “需要超过x值才能解压缩”、python-2.7 – 无法使用python和请求发布到solr服务器、Python带有参数的进程、python线程执行带有参数的任务的相关知识,请在本站搜索。

本文标签: