How do i POST to local host with requests library? - python

Im trying to make a post to the following url (http://localhost:1880/notifData) using python in a rpi. For this purpose im using bottle with no problems:
from bottle import get, post, run, request
#post('/notifData')
def notifData():
print(request.body.getvalue())
run(host='localhost', port=1880, debug=True)
But when I try to use the requests library im getting a [Errno 111] Conection refused error:
import requests
r = requests.post('http://localhost:1880/notifData/')
print(r.text)
Can someone explain why its not working?
Thanks in advance!

Requests raise a connection error when there is an event of a network-related issue such as DNS failure or connection refusal. Looking at your code and the error, I would suggest:
Making sure that the port (1880) is available for new connections,
Disabling proxy on localhost:
import os
os.environ['NO_PROXY'] = '127.0.0.1'
before sending the post request,
Use '127.0.0.1' instead of 'localhost' to send the post request.

Your post method handling function notifData is missing a return statement.
from bottle import get, post, run, request
#post('/notifData')
def notifData():
reqBody = request.body.getvalue()
print(reqBody)
return reqBody
run(host='localhost', port=1880, debug=True)
The URL path in the client code making call is incorrect. Remove the extra / at the end.
r = requests.post('http://localhost:1880/notifData')

Related

Flask Server not responding to HTTP POST Request

I built a simple flask server in order to automate python scripts based on an HTTP POST Request coming in from an outside service. This service sends these requests in response to events that we have created based on data conditions. All the flask server needs to do is parse the requests, and take the numerical value stored in the request and use it to run the corresponding python script. At one point, this system was working consistently. Fast forward a few months, the server was no longer working when tried again. No changes were made to the code. According to wireshark, The computer hosting the flask server is receiving the request to the correct port, but the request is now timing out. The host system is failing to respond to the request. Any Idea what is going on here? The firewall has temporarily been turned off.
Alternatively, is there another better package to achieve this goal with?
from flask import Flask, request
import threading
import runpy
app = Flask(__name__)
#app.route('/', methods=['POST'])
def PostHandler():
directory = {}
with open(r"M:\redacted") as f:
for line in f:
(key,val) = line.split()
directory[int(key)] = val
print(directory)
path = r"M:\redacted"
content = request.json
content = content['value']
print(content)
sel_script = int(content)
print(directory[sel_script])
runpy.run_path(path_name=path + directory[sel_script])
return
app.run(host="10.244.xx.xx", port=8080, threaded=True)

flask proxy for ttyd

I am looking for a method to write a simple proxy in flask for ttyd which is an open-source web terminal(https://github.com/tsl0922/ttyd). The most immediate way is to read client request and relay to ttyd server. However, it fails when the websocket is connecting.
My view function is as follows:
#app.route('/')
#app.route('/auth_token.js')
#app.route('/ws')
def ttyd():
if request.path=='/ws':
url = 'ws://192.168.123.172:7681' + request.path
else:
url = 'http://192.168.123.172:7681' + request.path
method = request.method
data = request.data or request.form or None
cookies = request.cookies
headers = request.headers
with closing(
requests.request(method, url, headers=headers, data=data, cookies=cookies)
) as r:
resp_headers = []
for name, value in r.headers.items():
resp_headers.append((name, value))
return Response(r, status=r.status_code, headers=resp_headers)
As you can see, the view function will handle 3 url requests, the first two succeed with status code 200, the third fails with status code 500. The error code in server side is as follows:
requests.exceptions.InvalidSchema: No connection adapters were found for 'ws://192.168.123.172:7681/ws'
I also check the network in two cases(with/without proxy). The picture 'without proxy' means direct type 'http://192.168.123.172:7681', it succeeds. The picture 'with proxy' means access ttyd server with flask proxy, it fails.
Without proxy
With proxy
Since I am new to flask and websocket, I am confused about the result. The sHTTPe flask proxy can handle any other http request(e.g. access google.com) but fails in WebSocket connection.
Thank you for telling me why and how can I fix it?
According to Websockets in Flask there is a flask-sockets project at https://github.com/heroku-python/flask-sockets to serve a websocket-endpoint in flask. To make the backend websocket connection to the server you can't use requests but websocket-client, see How do I format a websocket request?.
When I had this problem I solved it using the autobahn-python project, see https://github.com/arska/stringreplacingwebsocketproxy/
Cheers,
Aarno

pycURL; Received HTTP code 400 from proxy after CONNECT

I'm using pycURL to make a few requests to a https site through a http proxy.
Here's my code:
import pycurl
buf = cStringIO.StringIO()
c = pycurl.Curl()
c.setopt(c.URL, url) # 'url' is the base url of the form https://www.target.com
c.setopt(c.PROXY, proxy) # 'proxy' has the form 1.2.3.4:8080
c.setopt(c.WRITEFUNCTION, buf.write)
c.perform()
I've tried this code with different proxies. I get either Proxy CONNECT aborted or Received HTTP code 400 from proxy after CONNECT.
Is there something I'm missing? Should I be using https proxies instead? I've looked around and can't seem to find any help or documentation on pycURL's usage.
Any help appreciated. Thanks!
I have a problem similar to yours, and my error log is:
fatal: unable to access 'https://github.com/nhn/raphael.git/': Received HTTP code 400 from proxy after CONNECT
so i use these commond to resolve my problem,
first view your git profile
git config --global --edit
then to delete
config [remote "origin"]
proxy = https://github.com/facette/facette.git

Python Requests Post is Stuck at Starting New HTTP Connection

user_info = json.dumps({"bio":biography, "interests":interest_indexes})
headers = {'Content-type':'application/json'}
url = "http://0.0.0.0:5000/users/" + str(user_id)
r = requests.post("http://0.0.0.0:5000/users/1", data=user_info, headers=headers)
I've enabled logging and this is in Flask. If I manually do a POST request to the URL with the correct JSON response body, it works fine. It just says INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): 0.0.0.0
And it just hangs there forever.
Any ideas?
You need to run your flask app with threading enabled.
app.run(threaded=True)
This is not advisable for production of course, just for quick development :)

Http proxy works with urllib.urlopen, but not with requests.get [duplicate]

I am trying to do a simple get request through a proxy server:
import requests
test=requests.get("http://google.com", proxies={"http": "112.5.254.30:80"})
print test.text
The address of the proxy server in the code is just from some freely available proxy lists on the internet. The point is that this same proxy server works when I use it from browser, but it doesn't work from this program. And i tried many different proxy servers and none of them works through above code.
Here is what I get for this proxy server:
The requested URL could not be retrieved While trying to retrieve the URL: http:/// The following error was encountered:
Unable to determine IP address from host name for
The dnsserver returned: Invalid hostname
This means that: The cache was not able to resolve the
hostname presented in the URL. Check if the address is correct.
I know its an old question, but it should be
import requests
test=requests.get("http://google.com", proxies={"http":"http://112.5.254.30:80","https": "http://112.5.254.30:80"})
print (test.text)

Categories