将变量格式化为字符串

时间:2013-10-23 19:49:01

标签: python sql

我正在尝试创建一个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

3 个答案:

答案 0 :(得分:2)

creating parameters留给requests框架代替:

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)

答案 1 :(得分:0)

当您尝试格式化包含(意外)裸百分号的字符串时,也会出现错误消息“TypeError:float argument required not 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%”之后的“f”被解释为要求浮点数参数,而只是我的污点离开了第二个百分号。

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

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

我不幸的是,在2个嵌套的try-except中发生了几个调用层,因此错误显示距离引起它的行一英里。

答案 2 :(得分:-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