Am trying to generate a get request from a flask server to another, on destination side when I print the port, I keep getting random ports with each request
CLIENT:
from flask import Flask, redirect, request
import requests
app = Flask(__name__)
#app.route('/acqlock/<resource_name>')
def acquire_resource(resource_name):
print request.url
response = requests.get('http://127.0.0.1:8080/acqlock/' + resource_name)
return response.text
if __name__ == "__main__":
app.run(host="localhost", port=8081)
SERVER :
from flask import Flask, redirect, request
app = Flask(__name__)
#app.route('/')
#app.route('/acqlock/<resource_name>')
def acquire_lock(resource_name):
print request.url
print request.environ.get('REMOTE_PORT')
if __name__ == "__main__":
app.run(port=int("8080"))
it keeps printing http://127.0.0.1:8080/acqlock/file 58077 eventhough I was expecting it to print http://127.0.0.1:8081 8081 as the server is generating the request
This is normal. Remember that requests is the client here, it has to create a new HTTP connection to another server. TCP connections on the client side need a port as well, and when you create a socket to a remote server you are assigned a port number by the OS for the client-side of the connection.
That you are making this outgoing HTTP connection in the context of an incoming HTTP connection is neither here nor there. It is a different connection, in a different direction.
If you need to identify where the request came from, add information to the request. You can add custom headers, a cookie, query parameters, or post data.
Related
I have flask-socketio as backend and flutter as frontend. I am using flutter socket-io-client to connect to flask-socektio. It connects but I am receiving these continous messages on flask side
Sending packet PING data None
Received packet PONG data None
Sending packet PING data None
Received packet PONG data None
Sending packet PING data None
Received packet PONG data None
Sending packet PING data None
Received packet PONG data None ...... and so on
I wanted to get rid of this. How do I do it? also when I am sending/ emiting any data from frontend, the
socket.on('event' , (data)=>print(data) method prints null. So how do I send data from socketio event from backend to frontend? also I do I stop getting those messaged on PING PONG on server side?
Here is my flask code
from flask import Flask, request, jsonify
from flask_socketio import SocketIO
app = Flask(__name__)
app.secret_key = 'secret'
socketio = SocketIO(app,cors_allowed_origins="*")
app.debug = True
#app.route('/', methods=['GET'])
def index():
return 'Welcome!'
#socketio.on('connect')
def test_connect():
print('Client Connected')
#socketio.on('disconnect')
def test_disconnect():
print('Client disconnected')
#socketio.on('test')
def test():
print('Testing')
// i want to return some data to frontend here, how do I do it?
if __name__ == '__main__':
socketio.run(app,debug=True,host='0.0.0.0',port=5000)
Here is my flutter socket code
//using socket-io-client
IO.Socket socket = IO.io('http://192.16x.x.x:3000/', <String, dynamic>{
'transports': ['websocket']
});
socket.onConnect((_) {
print('connect');
});
scoket.on('test',(data)=>print(data)); //printing here the data received from backend
socket.onDisconnect((_) => print('disconnect'));
I have the similar problem in FastAPI (another Python framework similar with Flask).
Found a perfect solution here by using loguru.
This solution is for uvicorn web server, may need some change to suit Flask one
I have set up a tornado HTTP server which is working as a proxy server.
I am using the python requests library to use it as a proxy server.
When I try to fetch HTTP url's with it, it works fine. But it isn't intercepting HTTPS requests.
The proxy server part:
class ProxyServer(HTTPServerConnectionDelegate):
def start_request(self, server_conn, request_conn):
print('In start request')
return ClientDelegator(request_conn)
def on_close(self):
pass
def client_send_error(self):
self.write('Error happened.')
self.finish()
def main():
server = HTTPServer(ProxyServer())
server.bind(8888)
server.start(0)
tornado.ioloop.IOLoop.current().start()
if __name__ == "__main__":
main()
The requests part:
import requests
url = 'https://example.com'
proxy = {'http' : '127.0.0.1:8888'}
r = requests.get(url, proxies=proxy, verify=False)
print(r.text)
When I use http://example.com, the connection starts as 'In start request' gets printed. However, when I use https://example.com then the connection doesn't start. The ProxyServer doesn't enter start_request.
What am I doing wrong?
Your proxy variable only specifies a proxy for http, not https. You need to set the proxy for both protocols separately.
i am experimenting with flask and have a basic web page setup that gives me a data field to fill in. it all works ok, but i am having a problem with sending data via a socket connection to a server. the code is below:
from flask import Flask, render_template, request
import socket
import sys
app = Flask(__name__)
app.static_folder = 'static'
HOST, PORT = '', 8888
#app.route('/')
def index():
return render_template("index.html")
#app.route('/success', methods=['POST'])
def success():
if request.method == 'POST':
if request.form['Update'] == 'Update':
messsage_name = request.form["message_name"]
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as soc:
# connect to server if we have a post
soc.connect((HOST, PORT))
soc.sendall(bytes(messsage_name + "\n", "utf-8"))
return render_template("index.html")
if __name__ == '__main__':
app.debug = True
app.run()
I want to open the socket once then send data via it each time the update button is pressed, at present the only way i can get it to work is keep opening the socket as in the above code in success. I don't want the socket to close until the flask app quits.
whats the best way to achieve my goal
thanks
I think your title is wrong. In your example there is no use of socketIO library.
For using socketIO in your flask application, you need to install the library like this:
pip install flask-socketio
And then you can import it in your python file as:
from flask_socketio import SocketIO, emit
You can then use socketIO and emit some messages/data to your web page.
By the way your sockets, initialized as before, will live as long as your Flask server is on. More information available over there.
If your goal is to use the Python sockets, then you have to edit your question title.
I'm new to Twilio and I am trying to send and receive sms via python. Here is my code
import os
from twilio.rest import TwilioRestClient
from twilio import twiml
from flask import Flask, request, redirect
app = Flask(__name__)
port = int(os.environ.get('PORT', 5000))
# put your own credentials here
ACCOUNT_SID = "..."
AUTH_TOKEN = "..."
client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)
def respond (recipient, twilio_account, body):
message = client.messages.create(
to=recipient,
from_=twilio_account,
body=body,
)
#app.route('/sms', methods=['POST'])
def receive_sms():
number = request.form['From']
body = request.form['Body']
# print "Message received from {0} saying {1}".format(number, body)
response_message = "Message received from {0} saying {1}".format(number, body)
resp = twiml.Response()
resp.message(response_message)
return str(resp)
if __name__ == '__main__':
app.run(debug=True, host="0.0.0.0", port=port)
I keep getting a 11200 error everytime I text my Twilio number. What is happening?
This error indicates that Twilio didn't receive a response from your code within 15 seconds.
I don't see any reason your code would run slowly, but Twilio may not be able to access it at all. Have you taken any steps to let requests into your local network from the Internet?
One useful strategy is to use something like ngrok while you're still in development to tunnel traffic in from the outside world. After installing ngrok you can run
ngrok http 5000
to tunnel traffic in to your localhost port 5000. Then configure Twilio to connect to the ngrok tunnel.
I have written this HTTP web server in python which simply sends reply "Website Coming Soon!" to the browser/client, but I want that this web server should sends back the URL given by the client, like if I write
http://localhost:13555/ChessBoard_x16_y16.bmp
then server should reply back the same url instead of "Website Coming Soon!" message.
please tell how can I do this?
Server Code:
import sys
import http.server
from http.server import HTTPServer
from http.server import SimpleHTTPRequestHandler
#import usb.core
class MyHandler(SimpleHTTPRequestHandler): #handles client requests (by me)
#def init(self,req,client_addr,server):
# SimpleHTTPRequestHandler.__init__(self,req,client_addr,server)
def do_GET(self):
response="Website Coming Soon!"
self.send_response(200)
self.send_header("Content-type", "application/json;charset=utf-8")
self.send_header("Content-length", len(response))
self.end_headers()
self.wfile.write(response.encode("utf-8"))
self.wfile.flush()
print(response)
HandlerClass = MyHandler
Protocol = "HTTP/1.1"
port = 13555
server_address = ('localhost', port)
HandlerClass.protocol_version = Protocol
try:
httpd = HTTPServer(server_address, MyHandler)
print ("Server Started")
httpd.serve_forever()
except:
print('Shutting down server due to some problems!')
httpd.socket.close()
You can do what you're asking, sort of, but it's a little complicated.
When a client (e.g., a web browser) connects to your web server, it sends a request that look like this:
GET /ChessBoard_x16_y16.bmp HTTP/1.1
Host: localhost:13555
This assumes your client is using HTTP/1.1, which is likely true of anything you'll find these days. If you expect HTTP/1.0 or earlier clients, life is much more difficult because there is no Host: header.
Using the value of the Host header and the path passed as an argument to the GET request, you can construct a URL that in many cases will match the URL the client was using.
But it won't necessarily match in all cases:
There may be a proxy in between the client and your server, in which case both the path and hostname/port seen by your code may be different from that used by the client.
There may be packet manipulation rules in place that modify the destination ip address and/or port, so that the connection seen by your code does not match the parameters used by the client.
In your do_GET method, you can access request headers via the
self.headers attribute and the request path via self.path. For example:
def do_GET(self):
response='http://%s/%s' % (self.headers['host'],
self.path)