Python request convert string to JSON [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm using the requests library in Python to do a post request, but I'm having a problem when I read a value from a spreadsheet.
The following code works (returns a 201 status code):
url = 'http://myport:8092//api/Accounts/1000/Users'
item = {"firstName": "John", "lastName": "Smith", "userName": "JSmith"}
r = requests.post(url, json = item)
print(r.status_code)
As soon as I read "item" from a cell in a spreadsheet, a 501 error code gets returned. When I print out "item" after reading it from the spreadsheet, the output matches the value for item shown above.
I haven't been able to find a solution, the only thing I can think of is that the problem is that it's being read as a string?
Do I need to convert it into a json object before I run the post?

501 is the error code for not implemented. It looks like the url you're sending to doesn't accept post requests. Is the url correct?

Related

TypeError: JSON string indices must be integers [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 months ago.
Improve this question
I am currently working on getting data from a json URL. I was able to get the data displayed on my local host and I was able to get the only object I need which was data in archive[0]. I am only trying to get the service name, summary and date, but I am getting a
TypeError: string indices must be integers.
any tips on how I can only get those items? Thank you!
return render_template('index.html', data=json.dumps(
data['archive'][0]['service_name']['date']['summary']))
from json data:
{
"archive": [
{
"service_name": "AWS Sign-In (N. Virginia)",
"summary": "[RESOLVED] Increased Latencies for SAML Sign-In",
"date": "1623264111",
"status": "1",
"details": "",
}
There is no way to add extra indexes after "service_name", as it returns already a string. Dictionaries don't work in such a way that you can get different keys just by adding them after eachother, this would not make sense programatically. You should therefore create a new dictionary with the keys you want.
return render_template('index.html',
data=json.dumps({
'service_name': data['archive'][0]['service_name'],
'date': data['archive'][0]['date'],
'summary': data['archive'][0]['summary']
}))
If it is not a problem that the "status" and "details" keys also get into the dictionary, you can also pass in the whole dictionary.
return render_template('index.html',
data=json.dumps(data['archive'][0]))

KeyError When JSON Parsing [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I tried to access 'gold_spent` key in some dictionary made from JSON file.
Here is my code:
import json
import requests
response = requests.get("https://sky.shiiyu.moe/api/v2/profile/tProfile")
json_data = json.loads(response.text)
print(json_data['gold_spent'])
When I run this I get this "KeyError: 'gold_spent'"
I don't know what I am doing wrong, any help would be appreciated.
The data you are looking for is nested. See below.
print(json_data['profiles']['590cedda63e145ea98d44015649aba30']['data']['misc']['auctions_buy']['gold_spent'])
output
46294255
You experienced an exception because gold_spent isn't at all a key of first level, you need to investigate the structure to find it. Accessing non-existing key in the dictionary would always end with KeyError exception.
import json
import requests
response = requests.get("https://sky.shiiyu.moe/api/v2/profile/tProfile")
json_data = json.loads(response.text)
print(json_data.keys())
# dict_keys(['profiles'])
print(json_data['profiles'].keys())
# dict_keys(['590cedda63e145ea98d44015649aba30'])
print(json_data['profiles']['590cedda63e145ea98d44015649aba30'].keys())
# dict_keys(['profile_id', 'cute_name', 'current', 'last_save', 'raw', 'items', 'data'])
print(json_data['profiles']['590cedda63e145ea98d44015649aba30']['data']['misc']['auctions_buy']['gold_spent'])
# 46294255

Looping a function with its input being a url [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
So I am trying to get into python, and am using other examples that I find online to understand certain functions better.
I found a post online that shared a way to check prices on an item through CamelCamelCamel.
They had it set to request from a specific url, so I decided to change it to userinput instead.
How can I just simply loop this function?
It runs fine afaik once, but after the inital process i get 'Process finished with exit code 0', which isn't necessarily a problem.
For the script to perform how I would like it to. It would be nice if there was a break from maybe, 'quit' or something, but after it processes the URL that was given, I would like it to request for a new URL.
Im sure theres a way to check for a specific url, IE this should only work for Camelcamelcamel, so to limit to only that domain.
Im more familiar with Batch, and have kinda gotten away with using batch to run my python files to circumvent what I dont understand.
Personally if I could . . .
I would just mark the funct as 'top:'
and put goto top at the bottom of the script.
from bs4 import BeautifulSoup
import requests
print("Enter CamelCamelCamel Link: ")
plink = input("")
headers = {'User-Agent': 'Mozilla/5.0'}
r = requests.get(plink,headers=headers)
data = r.text
soup = BeautifulSoup(data,'html.parser')
table_data = soup.select('table.product_pane tbody tr td')
hprice = table_data[1].string
hdate = table_data[2].string
lprice = table_data[7].string
ldate = table_data[8].string
print ('High price-',hprice)
print ("[H-Date]", hdate)
print ('---------------')
print ('Low price-',lprice)
print ("[L-Date]", ldate)
Also how could I find the difference from the date I obtain from either hdate or ldate, from today/now. How the dates I parsed they're strings and I got. TypeError: unsupported operand type(s) for +=: 'int' and 'str'.
This is really just for learning, any example works, It doesnt have to be that site in specific.
In Python, you have access to several different types of looping control structures, including:
while statements
while (condition) # Will execute until condition is no longer True (or until break is called)
<statements to execute while looping>
for statements
for i in range(10) # Will execute 10 times (or until break is called)
<statements to execute while looping>
Each one has its strengths and weaknesses, and the documentation at Python.org is very thorough but easy to assimilate.
https://docs.python.org/3/tutorial/controlflow.html

How to access webpage with variables in python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have a project and want to access a url by python. If i have variable1=1 and variable2=2, I want an output to be like this:
www.example.com/data.php?variable1=1&variable2=2
How do I achieve this? Thanks!
Check this out:
try:
from urllib2 import urlopen # python 2
except:
from urllib.request import urlopen # python 3
vars = ['variable1=1', 'variable2=2']
for i in vars:
url = 'http://www.example.com/data.php?' + i
response = urlopen(url)
html = response.read()
print(html)
The first four lines import some code we can use to make a HTTP request.
Then we create a list of variables named vars.
Then we pass each of those variables into a loop; that loop will run once for each item in vars.
Next we build the url given the current value in vars.
Finally we get the html at that address and print it to the terminal.
You can use formate operation in python for string.
for example
variable1=1
variable1=1
url = 'www.example.com/data.php?variable1={}&variable2={}'.format(variable1,variable1)
or if you want to use the url with request then you can make a dict and pass it in request like this way
import requests
url = 'http://www.example.com/data.php'
data = {'variable1':'1','variable2':'2'}
r = requests.get(url,data)
and it will making request on this url
http://www.example.com/data.php?variable1=1&variable2=2
Try string formatting...
url = 'www.example.com/data.php?variable1={}&variable2={}'.format(variable1, variable2)
This means the 2 {} will be replaced with whatever you pass in .format(), which in this case is just the variables' values

Python Shelve like requirement [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I want to store some kind of persistent tracking to my application. Like for example ,
application.py supports 3 arguments, --firstarg --secondarg --thirdarg.
user can execute application.py using either one of the argument. I want to provide a feature where in user can track that he has already completed running the firstarg. In order to achieve this, i wanted to store a file called status.log, where the tracker will be stored.
Initially, status.log has
firstarg : 0
secondarg : 0
thirdarg : 0
once the user executes the first arg, it should turn the line , firstarg : 1
so when users wants, he can check if he has already completed running the firstarg or not.
Is it possible ?
I tried shelve, its not working for me for some reason. I am not seeing any logs written to the file.
Thanks.
I'd say use a JSON file as a persistent store and use the load and dump methods for reads and writes.
The JSON method is built in so all you need is to import it and use it:
import json
data_file = '/path/to/file'
# Load current state from file
contents = json.load(data_file)
# Do something
# ....
# ....
# Change values
contents['firstarg'] = firstarg
# Save to file
json.dump(contents, data_file)
Since you don't have a code sample, this is a simple approach

Categories

Resources