2013-10-23 53 views
-2

我想创建一个Python程序,它将查询一个URL并生成一个JSON文件。我需要在来自SQL查询的URL末尾传递一个参数。格式化一个字符串变量

我导入了requests库。

当我尝试在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&paramid=%d' % col1 
    user = 'abc' 
    password ='testgo' 
    data = requests.get(url, auth=(user, password)) 
    json_data=data.json() 
    print json_data 
+1

... Python还告诉你*错误在哪里(并且推断它与URL或参数传递无关)。 –

+0

你实际上不得不离开你的方式来得到这个错误,首先使用'%d'而不是'%s'来表示“我绝对肯定希望这只能使用数字而不是字符串”,然后执行'col1 = str(col)'说“我绝对肯定希望这是一个字符串,而不是一个数字”。然后,当Python说“嘿,那个字符串不是数字”时,你不明白吗? (也许它们都是_actually_意思是“我复制并粘贴了这行代码而根本不理解它”) – abarnert

回答

2

离开creating parametersrequests框架来代替:

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) 
+0

它说:TypeError:'long'对象没有属性'__getitem__'。你能显示完整的代码吗? – Rio

+0

然后我们把它串起来;更新。 –

+0

仍然没有运气:TypeError:'long'对象没有属性'__getitem__'。我们从表中获取整数值并传递到url – Rio

0

错误消息'TypeError:float argument require d,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 
>>> 

的“F”“100%”被解释为要求一个浮点参数,而这是简单地我smudgefingers离开断第二百分号之后。

>>> print "fail 100%% for serverid|%s| " % ("a") 
fail 100% for serverid|a| 
>>> 

工作正常。如果“100%”后面的单词以d或o或s开头,则会得到稍微不同的错误消息。

我很不幸地发生了这样的情况,在一个2嵌套的try-except内部发生了几个调用层,所以这个错误出现在距离引起它一英里的地方。

-1
print ("float_value : %f , digit_value : %d , string_value : %s" % (3.4, 5, 'somestring')) 
float_value : 3.400000 , digit_value : 5 , string_value : somestring 
+0

你能补充一些解释吗? – pableiros