Problems with flask and bad request - flask

I was programming myself a pretty nice api to get some json data from my gameserver to my webspace using json,
but everytime i am sending a request using angular i am getting this:
127.0.0.1 - - [20/Mar/2018 17:07:33] code 400, message Bad request version
("▒\x9c▒▒{▒'\x12\x99▒▒▒\xadH\x00\x00\x14▒+▒/▒,▒0▒\x13▒\x14\x00/\x005\x00")
127.0.0.1 - - [20/Mar/2018 17:07:33] "▒\x9dtTc▒\x93▒4▒M▒▒▒▒▒\x9c▒▒{▒'\x99▒▒▒▒H▒+▒/▒,▒0▒▒/5"
HTTPStatus.BAD_REQUEST -
127.0.0.1 - - [20/Mar/2018 17:07:33] code 400, message Bad request syntax
('\x16\x03\x01\x00▒\x01\x00\x00\x9d\x03\x03▒k,&▒▒ua\x8c\x82\x17\x05▒QwQ$▒0▒▒\x9f▒B1\x98\x19W▒▒▒▒\x00\x00\x14▒+▒/▒,▒0▒\x13▒\x14\x00/\x005\x00')
127.0.0.1 - - [20/Mar/2018 17:07:33] "▒\x9d▒k,&▒▒ua\x8c\x82▒QwQ$▒0▒▒\x9f▒B1\x98W▒▒▒▒▒+▒/▒,▒0▒▒/5"
HTTPStatus.BAD_REQUEST -
127.0.0.1 - - [20/Mar/2018 17:07:33] code 400, message Bad request syntax
('\x16\x03\x01\x00▒\x01\x00\x00▒\x03\x03)▒▒\x1e\xa0▒\t\r\x14g%▒▒\x17▒▒\x80\x8d}▒F▒▒\x08U▒ġ▒▒\x06▒\x00\x00\x1c▒+▒/▒,▒0▒')
g%▒▒▒▒\x80\x8d}▒F▒U▒ġ▒▒▒▒+▒/▒,▒0▒" HTTPStatus.BAD_REQUEST -
My api
from flask import Flask, jsonify
from flaskext.mysql import MySQL
from flask_cors import CORS, cross_origin
app = Flask(__name__)
CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
cors = CORS(app, resources={r"/punishments": {"origins": "http://localhost:5000" "*"}})
mysql = MySQL()
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'test'
app.config['MYSQL_DATABASE_PASSWORD'] = 'Biologie1'
app.config['MYSQL_DATABASE_DB'] = 'test'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
#app.route('/punishments', methods=['GET'])
#cross_origin(origin='localhost:5000',headers=['Content- Type','Authorization'])
def get():
cur = mysql.connect().cursor()
cur.execute('''select * from test.punishments''')
r = [dict((cur.description[i][0], value)
for i, value in enumerate(row)) for row in cur.fetchall()]
return jsonify({'punishments' : r})
if __name__ == '__main__':
app.run()
My client function
export class ApiUserService {
private _postsURL = "https://localhost:5000/punishments";
constructor(private http: HttpClient) {
}
getPosts(): Observable<Punishments[]> {
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json; charset=utf-8');
return this.http
.get(this._postsURL,{
headers: {'Content-Type':'application/json; charset=utf-8'}
})
.map((response: Response) => {
return <Punishments[]>response.json();
})
.catch(this.handleError);
}
private handleError(error: Response) {
return Observable.throw(error.statusText);
}
}

I had the same error as yours.
My flask server was installed inside respberry-pi and I was trying to access it using https://ip:5000.
The problem was I was using https instead of http.
When I changed it to http://ip:5000, it worked.

I also faced same problem
use only http not https :-
http://ip:portnumber

Recently I also faced this, the problem came from the SSL config on my app.
In my .env I set the SSL_DISABLE to False, then I change it to True.
change SSL_DISABLE=False to SSL_DISABLE=True
So, the point here is are: check your URL, maybe be it something like: https://127.0.0.1:5000, just change it to http://127.0.0.1:5000.
Hope it helps to someone who also facing this issue in the future.

in my case, i was trying to debug SocketIo server running on flask. I was trying to access the server using wss:// which was causing the bad request. Changing it to ws:// resolved the issue.

In my case i resolve the problem reverting flask version to Flask==1.1.4 and jinja dependency to Jinja2==3.0.3

Related

Connection TimeOut in flutter when making a request to django Rest api locally

void reg() async {
try{
http.Response response = await http.get(Uri.parse("http://10.0.2.2/api/alluser"));
print(response.body);
}
catch(e){
print(e);
}
}
It is working when I am doing in chrome( web) http://127.0.0.1:8000 but not working in android emulator.
in Django's setting.py
ALLOWED_HOST = [10.0.2.2 , 127.0.0.1]
NOTE - Specific for connecting Android and django rest api in Flutter
I tried lot of things but connection timeout was occuring. I was using django Rest-Api
go to Command Prompt type ipconfig copy ipv4 address in my case 192.168.2.4.
add 192.168.2.4 in ALLOWED_HOST =[] in django settings.py.
type "python manage.py runserver 192.168.2.4:8000" to run your server.
4)In Flutter
your baseurl for accesing django rest api should be "http://192.168.2.4:8000/"
This worked for me . thanks

HTTP Deadline exceeded waiting for python Google Cloud Endpoints on python client localhost

I want to build a python client to talk to my python Google Cloud Endpoints API. My simple HelloWorld example is suffering from an HTTPException in the python client and I can't figure out why.
I've setup simple examples as suggested in this extremely helpful thread. The GAE Endpoints API is running on localhost:8080 with no problems - I can successfully access it in the API Explorer. Before I added the offending service = build() line, my simple client ran fine on localhost:8080.
When trying to get the client to talk to the endpoints API, I get the following error:
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/dist27/gae_override/httplib.py", line 526, in getresponse
raise HTTPException(str(e))
HTTPException: Deadline exceeded while waiting for HTTP response from URL: http://localhost:8080/_ah/api/discovery/v1/apis/helloworldendpoints/v1/rest?userIp=%3A%3A1
I've tried extending the http deadline. Not only did that not help, but such a simple first call on localhost should not be exceeding a default 5s deadline. I've also tried accessing the discovery URL directly within a browser and that works fine, too.
Here is my simple code. First the client, main.py:
import webapp2
import os
import httplib2
from apiclient.discovery import build
http = httplib2.Http()
# HTTPException happens on the following line:
# Note that I am using http, not https
service = build("helloworldendpoints", "v1", http=http,
discoveryServiceUrl=("http://localhost:8080/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest"))
# result = service.resource().method([parameters]).execute()
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.headers['Content-type'] = 'text/plain'
self.response.out.write("Hey, this is working!")
app = webapp2.WSGIApplication(
[('/', MainPage)],
debug=True)
Here's the Hello World endpoint, helloworld.py:
"""Hello World API implemented using Google Cloud Endpoints.
Contains declarations of endpoint, endpoint methods,
as well as the ProtoRPC message class and container required
for endpoint method definition.
"""
import endpoints
from protorpc import messages
from protorpc import message_types
from protorpc import remote
# If the request contains path or querystring arguments,
# you cannot use a simple Message class.
# Instead, you must use a ResourceContainer class
REQUEST_CONTAINER = endpoints.ResourceContainer(
message_types.VoidMessage,
name=messages.StringField(1),
)
package = 'Hello'
class Hello(messages.Message):
"""String that stores a message."""
greeting = messages.StringField(1)
#endpoints.api(name='helloworldendpoints', version='v1')
class HelloWorldApi(remote.Service):
"""Helloworld API v1."""
#endpoints.method(message_types.VoidMessage, Hello,
path = "sayHello", http_method='GET', name = "sayHello")
def say_hello(self, request):
return Hello(greeting="Hello World")
#endpoints.method(REQUEST_CONTAINER, Hello,
path = "sayHelloByName", http_method='GET', name = "sayHelloByName")
def say_hello_by_name(self, request):
greet = "Hello {}".format(request.name)
return Hello(greeting=greet)
api = endpoints.api_server([HelloWorldApi])
Finally, here is my app.yaml file:
application: <<my web client id removed for stack overflow>>
version: 1
runtime: python27
api_version: 1
threadsafe: yes
handlers:
- url: /_ah/spi/.*
script: helloworld.api
secure: always
# catchall - must come last!
- url: /.*
script: main.app
secure: always
libraries:
- name: endpoints
version: latest
- name: webapp2
version: latest
Why am I getting an HTTP Deadline Exceeded and how to I fix it?
On your main.py you forgot to add some variables to your discovery service url string, or you just copied the code here without it. By the looks of it you were probably suppose to use the format string method.
"http://localhost:8080/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest".format(api='helloworldendpoints', apiVersion="v1")
By looking at the logs you'll probably see something like this:
INFO 2015-11-19 18:44:51,562 module.py:794] default: "GET /HTTP/1.1" 500 -
INFO 2015-11-19 18:44:51,595 module.py:794] default: "POST /_ah/spi/BackendService.getApiConfigs HTTP/1.1" 200 3109
INFO 2015-11-19 18:44:52,110 module.py:794] default: "GET /_ah/api/discovery/v1/apis/helloworldendpoints/v1/rest?userIp=127.0.0.1 HTTP/1.1" 200 3719
It's timing out first and then "working".
Move the service discovery request inside the request handler:
class MainPage(webapp2.RequestHandler):
def get(self):
service = build("helloworldendpoints", "v1",
http=http,
discoveryServiceUrl=("http://localhost:8080/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest")
.format(api='helloworldendpoints', apiVersion='v1'))

Python: Accessing HTTPS url over Proxy using Requests

import shutil
import requests
import json
proxy = {
'user' : 'user',
'pass' : 'password',
'host' : "test.net",
'port' : 8080
}
url = 'https://github.com/timeline.json'
response = requests.get(url,verify=True, proxies={"https" : \
"http://%(user)s:%(pass)s#%(host)s:%(port)d" % proxy})
with open(r'..\test.json','wb') as out_file:
out_file.write(response.text)
print response
I'm trying to access a HTTPS link (e.g https://github.com/timeline.json) over proxy in office environment using Requests.
Accessing HTTP link seems to be working fine. Getting SSL error in HTTPS.
Please suggest what's missing in the code. Thanks!
Error received:
raise SSLError(e)
requests.exceptions.SSLError: [Errno 8] _ssl.c:504: EOF occurred in violation of protocol
I am using almost the same code you provided, and searched an proxy server. Everything is OK with me.
Try to take a look at document here requests proxies. And notice that https://github.com/timeline.json is deprecated by Github,try https://api.github.com/events
According to doc:
To use HTTP Basic Auth with your proxy, use the http://user:password#host/ syntax:
proxies = {
"http": "http://user:pass#10.10.1.10:3128/",
}
Are you missing a / at the end? Take a try.
import requests
url = 'https://api.github.com/events'
proxy = {
"http" : "http://211.162.xxx.xxx:80"
}
response = requests.get(url, verify=True, proxies=proxy)
print response.status_code
if response.status_code == requests.codes.ok:
response.encoding = 'utf-8'
jsontxt = response.json()
print jsontxt

Python requests 503 erros when trying to access localhost:8000

I am facing a bit of a situation,
Scenario: I got a django rest api running on my localhost:8000 and I want to access the api using my command line. I have tried urllib2 and python requests libs to talk to the api but failed(i'm getting a 503 error). But when I pass google.com as the url, I am getting the expected response. So I believe my approach is correct but I'm doing something wrong. please see the code below :
import urllib, urllib2, httplib
url = 'http://localhost:8000'
httplib.HTTPConnection.debuglevel = 1
print "urllib"
data = urllib.urlopen(url);
print "urllib2"
request = urllib2.Request(url)
opener = urllib2.build_opener()
feeddata = opener.open(request).read()
print "End\n"
Envioroments:
OS Win7
python v2.7.5
Django==1.6
Markdown==2.3.1
colorconsole==0.6
django-filter==0.7
django-ping==0.2.0
djangorestframework==2.3.10
httplib2==0.8
ipython==1.0.0
jenkinsapi==0.2.14
names==0.3.0
phonenumbers==5.8b1
requests==2.1.0
simplejson==3.3.1
termcolor==1.1.0
virtualenv==1.10.1
Thanks
I had a similar problem, but found that it was the company's proxy that was preventing from pinging myself.
503 Reponse when trying to use python request on local website
Try:
>>> import requests
>>> session = requests.Session()
>>> session.trust_env = False
>>> r = session.get("http://localhost:5000/")
>>> r
<Response [200]>
>>> r.content
'Hello World!'
If you are registering your serializers with DefaultRouter then your api will appear at
http://localhost:8000/api/ for an html view of the index
http://localhost:8000/api/.json for a JSON view of the index
http://localhost:8000/api/appname for an html view of the individual resource
http://localhost:8000/api/appname/.json for a JSON view of the individual resource
you can check the response in your browser to make sure your URL is working as you expect.

Working with django : Proxy setup

I have a local development django setup with apache. The problem is that on the deployment server there is no proxy while at my workplace I work behind a http proxy, hence the request calls fail.
Is there any way of making all calls from requests library go via proxy. [ I know how to add proxy to individual calls using the proxies parameter but is there a global solution ? ]
I got the same error reported by AmrFouad. At last, it fixed by updating wsgi.py as follows:
os.environ['http_proxy'] = "http://proxy.xxx:8080"
os.environ['https_proxy'] = "http://proxy.xxx:8080"
Add following lines in your wsgi file.
import os
http_proxy = "10.10.1.10:3128"
https_proxy = "10.10.1.11:1080"
ftp_proxy = "10.10.1.10:3128"
proxyDict = {
"http" : http_proxy,
"https" : https_proxy,
"ftp" : ftp_proxy
}
os.environ["PROXIES"] = proxyDict
And Now you can use this environment variable anywhere you want,
r = requests.get(url, headers=headers, proxies=os.environ.get("PROXIES"))
P.S. - You should have a look at following links
Official Python Documentation for Environment Variables
Where and how do I set an environmental variable using mod-wsgi and django?
Python ENVIRONMENT variables
UPDATE 1
You can do something like following so that proxy settings are only being used on localhost.
import socket
if socket.gethostname() == "localhost":
# do something only on local server, e.g. setting os.environ["PROXIES"]
os.environ["PROXIES"] = proxyDict
else:
# Set os.environ["PROXIES"] to an empty dictionary on other hosts
os.environ["PROXIES"] = {}