0

I am new to python. I have created a gui based app to insert values into database. I have created a Rest api to handle db operations. How can i append the api URL with json created in python.

app.py

from Tkinter import *
import tkMessageBox
import json
import requests
from urllib import urlopen


top = Tk()
L1 = Label(top, text="Title")
L1.pack( side = TOP)
E1 = Entry(top, bd =5)
E1.pack(side = TOP)


L2 = Label(top, text="Author")
L2.pack( side = TOP)
E2 = Entry(top, bd =5)
E2.pack(side = TOP)

L3 = Label(top, text="Body")
L3.pack( side = TOP)
E3 = Entry(top, bd =5)
E3.pack(side = TOP)
input = E2.get();

def callfunc():
data = {"author": E2.get(),
    "body" : E3.get(),
    "title" : E1.get()}
data_json = json.dumps(data)

# r = requests.get('http://localhost/spritle/api.php?action=get_uses')
#url = "http://localhost/spritle/api.php?action=insert_list&data_json="
#
url = urlopen("http://localhost/spritle/api.php?action=insert_list&data_json="%data_json).read()

tkMessageBox.showinfo("Result",data_json)
 SubmitButton = Button(text="Submit", fg="White", bg="#0094FF", 
                  font=("Grobold", 10), command = callfunc)
 SubmitButton.pack()


 top.mainloop()

Error:

TypeError: not all arguments converted during string formatting

i AM GETTING error while appending url with data_json ?

TorreZz
  • 115
  • 10

2 Answers2

0

There is an error on string formating:

Swap this:

"http://localhost/spritle/api.php?action=insert_list&data_json="%data_json

by this:

"http://localhost/spritle/api.php?action=insert_list&data_json=" + data_json

or:

"http://localhost/spritle/api.php?action=insert_list&data_json={}".format(data_json)

The following statements are equivalents:

"Python with " + "PHP"
"Python with %s" % "PHP"
"Python with {}".format("PHP")
"Python with {lang}".format(lang="PHP") 

Also, I don't think sending JSON data like this via URL is a good idea. You should encode the data at least.

felipsmartins
  • 13,269
  • 4
  • 48
  • 56
0

You are trying to use % operator to format the string, and you need to put the %s placeholder into the string:

"http://localhost/spritle/api.php?action=insert_list&data_json=%s" % data_json

Or use other methods suggested in another answer.

Regarding the data transfer - you definitely need to use POST request and not GET. Check this, using urllib2 and this, using requests.

Community
  • 1
  • 1
Borys Serebrov
  • 15,636
  • 2
  • 38
  • 54