I have a two servers. Is it possible to run the flask from e.g (192.168.1.1) using host = "192.168.1.2"
i got errors
Traceback (most recent call last):
File "app.py", line 38, in <module>
debug=True
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 772, in run
run_simple(host, port, self, **options)
File "/usr/local/lib/python2.7/site-packages/werkzeug/serving.py", line 706, in run_simple
test_socket.bind((hostname, port))
File "/usr/local/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 99] Cannot assign requested address
here is my code. from .e.g 192.168.1.1
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
#app.route('/index')
def index():
return render_template('index.html')
#app.route('/_add_numbers')
def add_numbers():
a = request.args.get('a', 0, type=int)
b = request.args.get('b', 0, type=int)
return jsonify(result=a + b)
if __name__ == '__main__':
app.run(
host="192.168.1.2",
port=int("80"),
debug=True
)
This seems to be a misunderstanding on how networking works... You cannot use the IP address of another server as your own, for the same reason you cannot invite people to your neighbor's house and expect them to end up at your door.
If you want to handle web requests on both servers, you are going to need load balancing. Or, a reverse proxy that proxies requests from one server to the other.
Related
The code below works as expected and runs without problem:
import socketio
import eventlet
port = 5000
sio = socketio.Server()
app = socketio.WSGIApp(sio, static_files={})
#sio.event
def connect(sid, environ):
print('Connect')
eventlet.wsgi.server(eventlet.listen(('', port)), app) # Note this line
However, as soon as the final line is wrapped in a function, an error occurs
import socketio
import eventlet
port = 5000
sio = socketio.Server()
app = socketio.WSGIApp(sio, static_files={})
#sio.event
def connect(sid, environ):
print('Connect')
def run():
eventlet.wsgi.server(eventlet.listen('', port), app) # Note this line
run()
This is the full error message:
Traceback (most recent call last):
File "/home/thatcoolcoder/coding/micro-chat/tester3.py", line 16, in <module>
run()
File "/home/thatcoolcoder/coding/micro-chat/tester3.py", line 14, in run
eventlet.wsgi.server(eventlet.listen('', port), app)
File "/usr/lib/python3.9/site-packages/eventlet/convenience.py", line 49, in listen
sock = socket.socket(family, socket.SOCK_STREAM)
File "/usr/lib/python3.9/site-packages/eventlet/greenio/base.py", line 136, in __init__
fd = _original_socket(family, *args, **kwargs)
File "/usr/lib/python3.9/socket.py", line 232, in __init__
_socket.socket.__init__(self, family, type, proto, fileno)
OSError: [Errno 97] Address family not supported by protocol
How can I prevent this? I'm building a small chat app and to keep things clean, I need to create and run the server from within a function (specifically a class method).
The issue is in this line:
eventlet.wsgi.server(eventlet.listen('', port), app)
This line should be:
eventlet.wsgi.server(eventlet.listen(('', port)), app)
Updated Code:
import socketio
import eventlet
port = 5000
sio = socketio.Server()
app = socketio.WSGIApp(sio, static_files={})
#sio.event
def connect(sid, environ):
print('Connect')
def run():
eventlet.wsgi.server(eventlet.listen(('', port)), app) # Note this line
run()
Output:
Explanation:
The eventlet.listen() is a param of eventlet.wsgi.server(), and the eventlet.listen() means listen which address and port.
The ('', 8000) combine the address and port. If we do not set the first param, it will be default 0.0.0.0.
If we set the localhost it will be look back address 127.0.0.1 and we also can set a IP address of our computer.
So for our last coding projects we've set up a web API that runs on local host. But now he has set up a virtual server for us to use along with usernames and passwords to use as well as which ports we are alllowed to use. I have my current code here. On the last line it used to be localhost and the port was 8080 but I changed it to reflect the new server we were given. However, it doesn't work and I couldn't seem to find a solution online. I also have the IP address and it didn't work either. I wasn't sure how to add my username and password to the mix as well as I am sure it is needed to access the server.
from flask_cors import CORS
import os
from flask import Flask, jsonify, make_response, Blueprint
from flask_swagger_ui import get_swaggerui_blueprint
from routes import request_api
import ssl
context = ssl.SSLContext()
context.load_cert_chain('certificate.pem', 'key.pem')
APP = Flask(__name__)
SWAGGER_URL = '/swagger'
API_URL = '/static/swagger.json'
SWAGGERUI_BLUEPRINT = get_swaggerui_blueprint(
SWAGGER_URL,
API_URL,
config={
'app_name': "Kales Flask Project"
}
)
APP.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix=SWAGGER_URL)
APP.register_blueprint(request_api.get_blueprint())
#APP.errorhandler(400)
def handle_400_error(_error):
return make_response(jsonify({'error': 'Misunderstood'}), 400)
#APP.errorhandler(404)
def handle_404_error(_error):
return make_response(jsonify({'error': 'Not found'}), 404)
#APP.errorhandler(401)
def handle_401_error(_error):
return make_response(jsonify({'error': 'Invalid Key Provided'}), 401)
if __name__ == '__main__':
CORS = CORS(APP)
APP.run(host='easel4.cs.utsarr.net', port=int(os.environ.get('PORT', 12145)), ssl_context=context)
Here is the output when I attempt to run this code
C:\Users\kingk\PycharmProjects\AdvanceSoft>python webapi.py
* Serving Flask app "webapi" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: off
Traceback (most recent call last):
File "webapi.py", line 44, in <module>
APP.run(host='10.100.201.3', port=12145, ssl_context=context)
File "C:\Users\kingk\PycharmProjects\AdvanceSoft\yes\lib\site-packages\flask\app.py", line 943, in run
run_simple(host, port, self, **options)
File "C:\Users\kingk\PycharmProjects\AdvanceSoft\yes\lib\site-packages\werkzeug\serving.py", line 1009, in run_simple
inner()
File "C:\Users\kingk\PycharmProjects\AdvanceSoft\yes\lib\site-packages\werkzeug\serving.py", line 962, in inner
fd=fd,
File "C:\Users\kingk\PycharmProjects\AdvanceSoft\yes\lib\site-packages\werkzeug\serving.py", line 805, in make_server
host, port, app, request_handler, passthrough_errors, ssl_context, fd=fd
File "C:\Users\kingk\PycharmProjects\AdvanceSoft\yes\lib\site-packages\werkzeug\serving.py", line 698, in __init__
HTTPServer.__init__(self, server_address, handler)
File "C:\Users\kingk\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 452, in __init__
self.server_bind()
File "C:\Users\kingk\AppData\Local\Programs\Python\Python37\lib\http\server.py", line 137, in server_bind
socketserver.TCPServer.server_bind(self)
File "C:\Users\kingk\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 466, in server_bind
self.socket.bind(self.server_address)
OSError: [WinError 10049] The requested address is not valid in its context
I assume the host='easel4.cs.utsarr.net' is the problem. The Flask documentation of the run method of the Application object recommends:
host – the hostname to listen on. Set this to '0.0.0.0' to have the server available externally as well. Defaults to '127.0.0.1' or the host in the SERVER_NAME config variable if present.
I am trying to send data from client where I am using python-socketio as mentioend below
#Client.py
import time
import socketio
sio = socketio.Client(engineio_logger=True)
start_timer = None
# if __name__ == '__main__':
sio.connect('http://127.0.0.1:3000')
sio.wait()
sio.emit('connect', {"Data": "Device_id"})
and trying to on server which is using flask-socketio as mentioned below in code
#Server.py
from flask import Flask, render_template, request, jsonify
from flask_socketio import SocketIO
app = Flask(__name__)
# app.config['SECRET_KEY'] = "Social Distance Secret"
socket_app = SocketIO(app)
#socket_app.on('connect')
def handle_id(data):
print(data)
print(request.sid)
if __name__ == '__main__':
socket_app.run(app, debug=True, host='127.0.0.1', port=3000)
I am able to receive the sid but I am not able to fetch the parameters I have given in client.py while emitting to WebSocket
# Error Server.py
Traceback (most recent call last):
File "C:\Users\varul.jain\AppData\Local\Programs\Python\Python36\lib\site-packages\engineio\server.py", line 545, in _trigger_event
return self.handlers[event](*args)
File "C:\Users\varul.jain\AppData\Local\Programs\Python\Python36\lib\site-packages\socketio\server.py", line 721, in _handle_eio_connect
return self._handle_connect(sid, '/')
File "C:\Users\varul.jain\AppData\Local\Programs\Python\Python36\lib\site-packages\socketio\server.py", line 626, in _handle_connect
self.environ[sid])
File "C:\Users\varul.jain\AppData\Local\Programs\Python\Python36\lib\site-packages\socketio\server.py", line 708, in _trigger_event
return self.handlers[namespace][event](*args)
File "C:\Users\varul.jain\AppData\Local\Programs\Python\Python36\lib\site-packages\flask_socketio-4.3.1.dev0-py3.6.egg\flask_socketio\__init__.py", line 283, in _handler
*args)
File "C:\Users\varul.jain\AppData\Local\Programs\Python\Python36\lib\site-packages\flask_socketio-4.3.1.dev0-py3.6.egg\flask_socketio\__init__.py", line 711, in _handle_event
ret = handler()
TypeError: handle_id() missing 1 required positional argument: 'data'
# Errors client.py:
Attempting polling connection to http://127.0.0.1:3000/socket.io/?transport=polling&EIO=3
Traceback (most recent call last):
File "C:/Users/varul.jain/Desktop/people_counter/listenn.py", line 12, in <module>
sio.connect('http://127.0.0.1:3000')
File "C:\Users\varul.jain\AppData\Local\Programs\Python\Python36\lib\site-packages\socketio\client.py", line 279, in connect
six.raise_from(exceptions.ConnectionError(exc.args[0]), None)
File "<string>", line 3, in raise_from
socketio.exceptions.ConnectionError: Unexpected status code 401 in server response
any suggestion will be really helpful
First problem is that you are using a connect event, but this event is reserved. Change the event name to something else:
#socket_app.on('connected')
def handle_id(data):
print(data)
print(request.sid)
The second problem is that in your client you are calling wait(), which blocks until the connection ends, so your emit() call will never get to run. Send the emit before the wait instead:
sio.connect('http://127.0.0.1:3000')
sio.emit('connected', {"Data": "Device_id"})
sio.wait()
I am following Flask Web Development book by Miguel Grinberg and I ran into an issue with his Email chapter.
These are his configurations:
import os
# ...
app.config["MAIL_SERVER"] = "smtp.googlemail.com"
app.config["MAIL_PORT"] = 587
app.config["MAIL_USE_TLS"] = True
app.config["MAIL_USERNAME"] = os.environ.get("MAIL_USERNAME")
app.config["MAIL_PASSWORD"] = os.environ.get("MAIL_PASSWORD")
After I set my environment variables I go into shell and try to run the following code:
(venv) $ flask shell
>>> from flask_mail import Message
>>> from hello import mail
>>> msg = Message("test email", sender="you#example.com", recipients=["you#example.com])
>>> msg.body = "This is plain text body"
>>> msg.html = "This is <b>HTML</b> body"
>>> with app.app_context():
... mail.send(msg)
...
My gmail is set up correctly, I followed the tutorial and did all the steps mentioned.
My code produced the following error:
Traceback (most recent call last):
File "<console>", line 2, in <module>
File "c:\...\flasky\venv\lib\site-packages\flask_mail.py", line 491, in send
with self.connect() as connection:
File "c:\...\flasky\venv\lib\site-packages\flask_mail.py", line 144, in __enter__
self.host = self.configure_host()
File "c:\...\flasky\venv\lib\site-packages\flask_mail.py", line 158, in configure_host
host = smtplib.SMTP(self.mail.server, self.mail.port)
File "C:\...\Python\Python37\lib\smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "C:\...\Python\Python37\lib\smtplib.py", line 336, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\...\Python\Python37\lib\smtplib.py", line 307, in _get_socket
self.source_address)
File "C:\...\Python\Python37\lib\socket.py", line 727, in create_connection
raise err
File "C:\...\Python\Python37\lib\socket.py", line 716, in create_connection
sock.connect(sa)
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or
established connection failed because connected host has failed to respond
I found another question that was raised about the same thing and I tried a couple of things that were suggested in there:
I changed the line
app.config["MAIL_SERVER"] = "smtp.googlemail.com"
to
app.config["MAIL_SERVER"] = "smtp.gmail.com"
and I hard coded "MAIL_USERNAME" and "MAIL_PASSWORD" variables but I got the same error again.
Due to nothing working and the previous question about this being very old (4 years) I thought it might be worth raising this again.
If anybody knows what I am doing wrong please let me know.
Thanks
Make sure you have allowed less secure apps to connect to your Google account.
Here is the link: https://myaccount.google.com/lesssecureapps
Try it with the following params:
app.config["MAIL_SERVER"] = "smtp.gmail.com"
app.config["MAIL_PORT"] = 465
Below is an example that works for me:
import os
from flask import Flask, jsonify
from flask_mail import Mail, Message
app = Flask(__name__)
app.config["MAIL_SERVER"]='smtp.gmail.com'
app.config["MAIL_PORT"]=587
app.config["MAIL_USE_TLS"]=False
app.config["MAIL_USE_SSL"]=True
app.config["MAIL_USERNAME"]=os.environ.get("MAIL_USERNAME")
app.config["MAIL_PASSWORD"]=os.environ.get("MAIL_PASSWORD")
mail = Mail(app)
msg = Message(
<your subject>,
sender=os.environ.get("MAIL_USERNAME"),
recipients=<recipiente e-mail>,
html=<your html template>
)
#app.route('/sendmail')
def publish():
mail.send(msg)
return jsonify({'message': 'Your message has been sent successfully'}), 200
if __name__ == '__main__':
app.run()
I am using flask to build a python web service, for example, I set the flask port as 8080 like this:
#app.route('/data', methods=['POST'])
def data_construct():
os.system('sh restart.sh')
if __name__ == '__main__':
app.debug = True
app.run(host='0.0.0.0', port=8080)
and the restart.sh is used for restarting an external service, but after I send a HTTP POST request to /data, the restart is successfully completed, but after a while, I get an error:
Traceback (most recent call last):
File "hello.py", line 87, in <module>
app.run(host='0.0.0.0', port=8080)
File "/home/work/.jumbo/lib/python2.7/site-packages/flask/app.py", line 739, in run
run_simple(host, port, self, **options)
File "/home/work/.jumbo/lib/python2.7/site-packages/werkzeug/serving.py", line 613, in run_simple
test_socket.bind((hostname, port))
File "/home/work/.jumbo/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
the 'restart.sh' is like this (storage is a C++-complied program):
killall storage
nohup ./storage &
and I find the external service is starting using the port 8080 which it is not supposed to do (its original port is still in use), how to solve this problem?