I have a front-end server that is getting some JSON data from my backend server. Both servers are running Django. This is the exact code that gets the json data..
def View(request):
r = requests.get(path)
return HttpResponse(r.json())
However, I am running into a strange problem today where the call completes successfully ONCE after restarting the server. If I run the following code: -
def View(request):
r = requests.get(path)
r = requests.get(path)
return HttpResponse(r.json())
This works successfully as well.
However, on the second time that View() is called, I get an error. This is what the error message says:
"uWSGI exceptions catcher for "GET /api/v1/backend/" (request plugin: "python", modifier1: 0)
Exception: TypeError: http header value must be a string
Exception class: TypeError
Exception message: http header value must be a string"
Clearly, the error is being thrown on my backend server, but I only changed some templates on the frontend today. I am at a loss as to what has caused this problem to start occurring today. Can anyone point me in the right direction?
give it the right json header:
return HttpResponse(data, content_type='application/json')
Related
I'm seeking help for this rather strange behaviour.
I have a Django view that gets called after a button click in a Django template
#require_http_methods(['GET', 'POST'])
#login_required
#transaction.atomic
def create_key(request, slug):
#some unrelated code
try:
r = requests.post(
some_url,
data={
#some_data
},
auth=(client_id, client_secret),
timeout=(req_to, res_to)
)
if r.status_code == 200:
return True
else:
return False
except ReadTimeout as to:
# handle exception
return True
except Exception as e:
# handle exception
return False
#some unrelated code
that basically calls an API endpoint to create a key.
Now the request with Postman works fine, taking out that python snippet and running it alone also works, but when put inside this Django view it hangs until reaches response timeout.
Does anybody has any idea or pointer on where the problem might be?
Thank you in advance!
EDIT: i've found similar problems but these while they share with me the same structure, the problem was somewhere else
Why Python requests library failing to get response?
LiveServerTestCase hangs at python-requests post call in django view
This question already has answers here:
How to POST JSON data with Python Requests?
(10 answers)
Closed 3 years ago.
I've wrote a little flask application.
I send a request with json data (python script) to the flask server (ubuntu 18.04 with python 3.6.7),
and the server evaluate these data...
Client:
data = { 'serial': '12345'
'printerConfig': {
'virtualPrinter1': 'physicalPrinter1',
'virtualPrinter2': 'physicalPrinter2',
'virtualPrinter3': 'physicalPrinter3'
}
}
r = requests.get("http://127.0.0.1/webservice", json=data)
Server:
#app.route('/', methods=['GET', 'POST'])
def webservice():
if request.method == 'GET':
serial = request.json['serial'] if 'serial' in request.json else None
printerConfig = request.json['printerConfig'] if 'printerConfig' in request.json else None
I have tested this code in pyCharm with the development server and always works fine.
After that I have tried to implement that to an Apache2 server.
Now I get the following error message in apache-error.log.
ERROR:flask.app:Exception on / [GET]
Traceback (most recent call last):
...
File "/var/www/html/webservice/webservice.py", line xx, in webservice
serial = request.json['serial'] if 'serial' in request.json else None
TypeError: argument of type 'NoneType' is not iterable
Print of request.json shows only None.
Exactly the same code on the development server is running.
Instead of request.json I also tried request.data, with the same result.
Is there a specially setting for the Apache2?
Has anyone an idea?
Best regards
flo
You are making a get request.
Try making a post request to your webservice
r = requests.post("http://127.0.0.1/webservice", json=data)
You will never include the json="" when making a get... that is for only posting/updating json to the webserver
Remember, GET in http terms is only for requesting content from a URL endpoint. POST is to send new content to the URL endpoint.
GET/POST
Another quick point... Try just printing request.json on your back end/flask app before the serial = request.json['serial'] if 'serial' in request.json else None etc... just to make sure that the data is arriving correctly upon being posted.
I'm using Stripe API and I'm trying to save the connect account keys in db. But I cannot save them successfully and a weird thing is happening.
My code is here
resp = stripe_connect_service.get_raw_access_token(method='POST', data=data)
connect_account_info = json.loads(resp.text)
connect_public_key = connect_account_info['stripe_publishable_key']
connect_access_token = connect_account_info['access_token']
connect_user_id = connect_account_info['stripe_user_id']
connect_refresh_token = connect_account_info['refresh_token']
print(connect_public_key)
print(connect_access_token)
print(connect_user_id)
print(connect_refresh_token)
form = Form()
if form.validate_on_submit():
data = Data(connect_public_key=connect_public_key, connect_access_token=connect_access_token, connect_user_id=connect_user_id, connect_refresh_token=connect_refresh_token)
db.session.add(data)
db.session.commit()
So after getting the token and finished submitting the form on the page rediercted from Stripe Connect page, I will save the data. print actually shows the connect account keys, but after submitting the form, the error says
connect_public_key = connect_account_info['stripe_publishable_key']
KeyError: 'stripe_publishable_key'
even though print does work.
And when I run debugger, the error says like this
{'error': 'invalid_grant', 'error_description': 'This authorization code has already been used.
How can I fix this error?
This error usually happens when your code incorrectly re-uses the authorization code (ac_XXXX) that you get in the URL.
This is often caused by refreshing the browser/page you're on after the redirect. Your code will fetch the code from the URL and use it to exchange it on the /oauth/token endpoint but if you do it twice it causes the connection to be revoked for security reasons.
In my case it was my server that retried on failure that eventually leads to this error response.
So in my case the problem was that my server's function crashed in a different place, after getting the token from the code.
And after the function crashed, since the server was setup for retry, it called the endpoint once again with the same params and in the second attempt the code was already used indeed, hence the error.
Maybe it can help someone too.
I'm trying to pull the event hubs metrics using the rest API,
after reading https://msdn.microsoft.com/en-us/library/azure/dn163589.aspx and https://msdn.microsoft.com/en-us/library/azure/mt652158.aspx
I have got python code that can actually call the url and get a response
I currently try the following code
def get_metrics(subscription, eventhub, cert, specific_partition=None):
apiversion = '2014-01'
namespace = eventhub['namespace']
eventhubname = eventhub['name']
url = "https://management.core.windows.net/{}/services/ServiceBus/Namespaces/{}/eventhubs/{}/Metrics/requests.total/Rollups/P1D/Values/?$filter=timestamp%20gt%20datetime'2016-04-09T00:00:00.0000000Z'&api-version={}".format(
subscription, namespace, eventhubname, apiversion)
request = requests.Request('GET', url, headers=DEFAULT_HEADERS).prepare()
session = requests.Session()
if cert is None or not os.path.isfile(cert):
raise ValueError('You must give certificate file')
session.cert = cert
result = session.send(request)
return result
my problem is with the url, when using the url in the code above I get
<Error xmlns="http://schemas.microsoft.com/windowsazure" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><Code>InternalError</Code><Message>The server encountered an internal error. Please retry the request.</Message></Error>
I can get the API to output all possible rollups and all possible metrics but when trying to get actual values it fails.
is there something wrong in the url or is it a bug in azure/azure documantation?
Usually, when we occur this issue, it means that there something wrong with the endpoint we combined for the Rest Apis, so that then service raise exception when parse the endpoint.
As compared with my successfully test, what the interesting I found is that the issue raised by the filter param timestamp whose first letter should be uppercased as Timestamp. The following endpoint works fine on my side. Hope it will be helpful to you.
url = "https://management.core.windows.net/{}/services/ServiceBus/Namespaces/{}/eventhubs/{}/Metrics/requests.total/Rollups/P1D/Values/?$filter=Timestamp%20gt%20datetime'2016-04-09T00:00:00.0000000Z'&api-version={}".format(
subscription, namespace, eventhubname, '2012-03-01')
I'm using the django test framwork to test my API. I have a simple view that returns "ok" at the address GET http://localhost:8000/v1/ping/. When I run the server and I test this with Chrome, it works well. However, when I launch a test on it, I get a 404 error. This is my test:
def test_ping(self):
c = Client()
response = c.get('/v1/ping/')
print response.content
print response.status_code
and the response:
<h1>Not Found</h1><p>The requested URL /v1/ping/ was not found on this server.</p>
404
The get method on Django's Test Client takes a relative path as an argument. Have you tried response = c.get('/v1/ping/')?
I found the error: I use rest_framework_swagger and there was a test file in it. I deleted it and everything is OK now.