Python 将变量格式化为字符串
我正在尝试创建一个Python程序,该程序将查询URL并生成JSON文件。我需要在来自SQL查询的URL的末尾传递一个参数 我已导入Python 将变量格式化为字符串,python,sql,Python,Sql,我正在尝试创建一个Python程序,该程序将查询URL并生成JSON文件。我需要在来自SQL查询的URL的末尾传递一个参数 我已导入请求库 当我试图在URL中传递参数时,我收到一条错误消息“TypeError:float argument required,not str” 查询只生成一列结果: id 2 3 4 下面是我的想法: import MySQLdb import requests con=MySQLdb.connect(host="localhost",user="test
请求
库
当我试图在URL中传递参数时,我收到一条错误消息“TypeError:float argument required,not str”
查询只生成一列结果:
id
2
3
4
下面是我的想法:
import MySQLdb
import requests
con=MySQLdb.connect(host="localhost",user="test", passwd="test", db ="mfg")
cur = con.cursor()
select=("select id from tblMfg")
cur.execute(select)
result=cur.fetchall()
for i in result:
col =i[0]
col1=str(col)
url = 'http://appl.xyz.net:8080/app/content/pq/doQuery?solution=nd&path=&file=Test.nd&dataAccessId=1¶mid=%d' % col1
user = 'abc'
password ='testgo'
data = requests.get(url, auth=(user, password))
json_data=data.json()
print json_data
请转到请求
框架:
params = {'solution': 'nd', 'path': '', 'file': 'Test.nd', 'dataAccessId': '1',
'paramid': str(col[0])}
url = 'http://appl.xyz.net:8080/app/content/pq/doQuery'
user = 'abc'
password ='testgo'
data = requests.get(url, auth=(user, password), params=params)
尝试格式化包含(意外)裸百分号的字符串时,也会出现错误消息“TypeError:float argument required,not str”。
例如:
>>> print "fail 100% for serverid|%s| " % ("a")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: float argument required, not str
>>>
很好。如果“100%”后面的单词以d、o或s开头,则会收到稍微不同的错误消息
我很不幸,在一个两层嵌套的try中有几个调用层发生了这种情况,所以错误出现在离导致它的线路一英里远的地方 …Python还告诉您错误在哪里(通过推断,它与URL或参数传递无关)。您实际上必须竭尽全力才能获得此错误,首先使用
%d
,而不是%s
,意思是“我绝对希望这只适用于数字,而不是字符串”,然后执行col1=str(col)
表示“我绝对希望这是一个字符串,而不是一个数字”。然后,当Python说“嘿,那个字符串不是数字”时,你不明白吗?(可能它们实际上都是指“我复制并粘贴了这行代码,但根本不理解它”?)它说:TypeError:“long”对象没有属性“getitem”。你能显示完整的代码吗?还是不走运:TypeError:“long”对象没有属性“getitem”。我们从表中获取整数值并将其传递到url@Rio:我使用一些变体进行了测试,params
可以有整数和长数值。您可以添加一些解释吗?
print ("float_value : %f , digit_value : %d , string_value : %s" % (3.4, 5, 'somestring'))
float_value : 3.400000 , digit_value : 5 , string_value : somestring
print ("float_value : %f , digit_value : %d , string_value : %s" % (3.4, 5, 'somestring'))
float_value : 3.400000 , digit_value : 5 , string_value : somestring