I am using nodejs to post a request to a python flask application, the node app is running on replit and the python app is running on vscode. I get this error in nodejs console:
[Error: connect ECONNREFUSED 127.0.0.1:3000] {
errno: -111,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3000
}
I've tried just about everything I can think of: changing port numbers, editing code, etc. Nothing has made a difference.
Here is the python code that I think must be causing the error somehow?
import cv2
import numpy as np
from flask import Flask, request, jsonify, after_this_request
import base64
app = Flask(__name__)
print('hello')
#app.route('/api/text', methods=['POST'])
def receive_text():
return 'hi'
if __name__ == '__main__':
app.run(host='0.0.0.0', port=3000,debug=True)
No errors show up when the programs are run, only in nodejs when the post is made to the flask app.
Trying the same things others have on their stack overflow questions, nothing has worked.
Please let me know if theres more info I can provide.
EDIT: I changed to connect to my IP rather than 127, and I have a different but similar and just as ambigious error.
errno: -110,
code: 'ETIMEDOUT',
syscall: 'connect',
address: 'IP',
port: 81
Is it possible to fix this, or do I have to actually host it somewhere that is not my computer at all for this to work?
Related
I am trying to set up bidirectional communication between my Flutter android project and a server written in Python/Flask.
The code on the python side is basically the same as can be found at https://flask-sock.readthedocs.io/en/latest/quickstart.html. ie.
from flask import Flask, render_template
from flask_sock import Sock
app = Flask(__name__)
sock = Sock(app)
#sock.route('/echo')
def echo(ws):
while True:
data = ws.receive()
ws.send(data)
On the Dart side, I have:
final channel = WebSocketChannel.connect(
Uri.parse('wss://10.0.2.2:5000/echo'),
);
And the dependency in the pubspec.yaml file is:
web_socket_channel: ^2.1.0
Running it I get the bizarre error message:
127.0.0.1 - - [23/Jul/2022 17:49:09] code 400, message Bad request version ('\x18±-8ÛF\x18Ã\x9b(ôP')
There is nothing wrong with the flask side of things, my app processes the standard html requests fine. But setting up the websockets causes these runtime complaints.
I tried flask.socketio and got the similar errors.
I am currently underway with my Senior Capstone project, in which I am to write a somewhat basic program which allows a custom interface on my iPhone6 device to remotely control or issue critical commands to a NIDS (Suricata) established at my home RaspberryPi(3B+) VPN. My question, however, is whether it's feasible to write said program which can allow remote access control of basic functions/response options on the Pi's IDS, given that I am utilizing it as a device within the VPN network. The main issue would be establish remote signaling to the iOS device whenever there is an anomaly and allowing it to respond back and execute root-level commands on the NIDS.
If it is of any good use, I am currently using Pythonista as a runtime environment on my mobile device and have set my VPN's connection methods to UDP, but I'm not sure if enabling SSH would assist me. I have a rather basic understanding of how to operate programming in regards to network connectivity. I very much appreciate any and all the help given!
from tkinter import *
window=Tk()
window.geometry("450x450")
window.title("IDS Response Manager")
label1=Label(window,text="Intrusion Response Options",fg= 'black',bg ='white',relief="solid",font=("times new roman",12,"bold"))
label1.pack()
button1=Button(window,text="Terminate Session",fg='white', bg='brown',relief=RIDGE,font=("arial",12,"bold"))
button1.place(x=50,y=110) #GROOVE ,RIDGE ,SUNKEN ,RAISED
button2=Button(window,text="Packet Dump",fg='white', bg='brown',relief=RIDGE,font=("arial",12,"bold"))
button2.place(x=220,y=110) #GROOVE ,RIDGE ,SUNKEN ,RAISED
button3=Button(window,text="Block Port",fg='white', bg='brown',relief=RIDGE,font=("arial",12,"bold"))
button3.place(x=110,y=170) #GROOVE ,RIDGE ,SUNKEN ,RAISED
Very basic options as are shown here.
You can use a flask server with an API, which you can send post requests to. You can then send get requests to receive the commands. To host your API, look at Heroku (free tier available, and very much functional, with already configured app_name.herokuapp.com).
Search up to send a post request with the technologies you are using to build your app. Send keyword command with the command to the /send_commands along with the password, "password_here" (changeable to anything you want).
Python:
Modules: Flask (server), request (client)
Server Code:
from flask import Flask
app = Flask(__name__)
commands = []
#app.route('/get_commands', methods=['GET'])
def get_commands():
tmp_commands = commands[::]
commands = []
return {'commands': tmp_commands}
#app.route('/send_commands', methods=['POST'])
def send_commands():
if request.json['password'] == "password_here":
commands.append(request.json['command'])
return {'worked': True}
else:
return {'worked': False}
if __name__ == '__main__':
app.run(debug=True)
Client Code:
import requests
URL = "url_here/get_commands"
commands = requests.get(url = URL)
for command in commands:
os.system(command)
I've uploaded some code into a server. The code was working locally but when I upload it to the server it gives me an Internal Server Error. The website is running with wsgi and the code is:
try:
from decksite import main, APP as application
except Exception as e:
from shared import repo
repo.create_issue('Error starting website', exception=e)
if __name__ == '__main__':
print('Running manually. Is something wrong?')
application.run(host='0.0.0.0', debug=False)
So both the try and the except are failing. I want to add a second exception and pass it all to a simple flask application that would output both exceptions to the browser and log them to a file. The problem is that I don't know how to pass the exception to the error_app flask app and that it breaks in the line where I set the logging config. Here is what I've done. I'm only getting NoneType: None instead of the full exception.
import os, sys
sys.path.append("/home/myuser/public_html/flask");
try:
from decksite import main, APP as application
except Exception as error:
#from shared import repo
#repo.create_issue('Error starting decksite', exception=error)
#sys.path.insert(0, os.path.dirname(__file__))
#from error_app import app as application
# This is the code that goes into the error flask application
import logging
import traceback
from flask import Flask, __version__
app = Flask(__name__)
application = app
#app.route("/")
def hello():
return traceback.format_exc()
# The next line gives Internal Server Error
logging.basicConfig(filename='example.log', level=logging.DEBUG)
logging.exception(error)
return traceback.format_exc()
if __name__ == '__main__':
print('Running manually. Is something wrong?')
application.run(host='0.0.0.0', debug=False)
I don't have sudo in the server and can't ssh to it so unless I'm able to log the errors I'm not going to be able to fix anything.
Edit: I've almost got it as I want:
.htaccess
website.wsgi
error_app.py
website/init.py
website/main.py
Create a custom 500 handler and print out the trackback
import traceback
#app.errorhandler(500)
def internal_server_error(e):
return render_template('500_error.html', traceback=traceback.format_exc())
Have your '500_error.html' template show you the traceback.
You mentioned 500 Internal Server Error is coming. Things are proper in your local but fail on server. Since you don't have ssh access, it might be tough to debug. If you use something like Docker or Kubernetes to build and deploy it can be useful. I can suggest you some ways to debug. The code is not going to try except and failing, the possible reason is the server itself not starting due to missing requirements say some import or it could be anything.
Debug Steps
Create a virtual environment and re-install requirements in it similar to your server. This will help you to identify if there is a missing requirement.
if you are environment is not production and you are testing the application in the server then put debug = True. It will show an error on the front end. This is definitely not a recommended approach. I am suggesting since you don't have ssh access.
If possible create a simple route say /hello and in that just return hello, and check whether it is returning you the right result or not. This will let you know whether your server is starting or not. Even this is not recommendable for production.
You can also check the flask app before request and after request. This might also be useful
Hopefully, 1st step debugging will help you a lot and you might not need to go to step 2 and step 3. I gave you for the worst-case scenario
I want to debug small flask server inside jupyter notebook for demo.
I created virtualenv on latest Ubuntu and Python2 (on Mac with Python3 this error occurs as well), pip install flask jupyter.
However, when I create a cell with helloworld script it does not run inside notebook.
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run(debug=True,port=1234)
File
"/home/***/test/local/lib/python2.7/site-packages/ipykernel/kernelapp.py",
line 177, in _bind_socket
s.bind("tcp://%s:%i" % (self.ip, port)) File "zmq/backend/cython/socket.pyx", line 495, in
zmq.backend.cython.socket.Socket.bind
(zmq/backend/cython/socket.c:5653) File
"zmq/backend/cython/checkrc.pxd", line 25, in
zmq.backend.cython.checkrc._check_rc
(zmq/backend/cython/socket.c:10014)
raise ZMQError(errno) ZMQError: Address already in use
NB - I change the port number after each time it fails.
Sure, it runs as a standalone script.
update without (debug=True) it's ok.
I installed Jupyter and Flask and your original code works.
The flask.Flask object is a WSGI application, not a server. Flask uses Werkzeug's development server as a WSGI server when you call python -m flask run in your shell. It creates a new WSGI server and then passes your app as paremeter to werkzeug.serving.run_simple. Maybe you can try doing that manually:
from werkzeug.wrappers import Request, Response
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == '__main__':
from werkzeug.serving import run_simple
run_simple('localhost', 9000, app)
Flask.run() calls run_simple() internally, so there should be no difference here.
The trick is to run the Flask server in a separate thread. This code allows registering data providers. The key features are
Find a free port for the server. If you run multiple instances of the server in different notebooks they would compete for the same port.
The register_data function returns the URL of the server so you can use it for whatever you need.
The server is started on-demand (when the first data provider is registered)
Note: I added the #cross_origin() decorator from the flask-cors package. Else you cannot call the API form within the notebook.
Note: there is no way to stop the server in this code...
Note: The code uses typing and python 3.
Note: There is no good error handling at the moment
import socket
import threading
import uuid
from typing import Any, Callable, cast, Optional
from flask import Flask, abort, jsonify
from flask_cors import cross_origin
from werkzeug.serving import run_simple
app = Flask('DataServer')
#app.route('/data/<id>')
#cross_origin()
def data(id: str) -> Any:
func = _data.get(id)
if not func:
abort(400)
return jsonify(func())
_data = {}
_port: int = 0
def register_data(f: Callable[[], Any], id: Optional[str] = None) -> str:
"""Sets a callback for data and returns a URL"""
_start_sever()
id = id or str(uuid.uuid4())
_data[id] = f
return f'http://localhost:{_port}/data/{id}'
def _init_port() -> int:
"""Creates a random free port."""
# see https://stackoverflow.com/a/5089963/2297345
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('localhost', 0))
port = sock.getsockname()[1]
sock.close()
return cast(int, port)
def _start_sever() -> None:
"""Starts a flask server in the background."""
global _port
if _port:
return
_port = _init_port()
thread = threading.Thread(target=lambda: run_simple('localhost', _port, app))
thread.start()
Although this question was asked long ago, I come up with another suggestion:
The following code is adapted from how PyCharm starts a Flask console.
import sys
from flask.cli import ScriptInfo
app = None
locals().update(ScriptInfo(create_app=None).load_app().make_shell_context())
print("Python %s on %s\nApp: %s [%s]\nInstance: %s" % (sys.version, sys.platform, app.import_name, app.env, app.instance_path))
Now you can access app and use everything described in the Flask docs on working with the shell
I have a python app developed on Flask. Everything works fine offline, I tried deploying on CherryPy successfully too. Now, I'm trying to deploy the same on www.pythonanywhere.com.
Here's the deploy.py I use for deploying the Flask app on CherryPy
from cherrypy import wsgiserver
from appname import app
def initiate():
app_list = wsgiserver.WSGIPathInfoDispatcher({'/appname': app})
server = wsgiserver.CherryPyWSGIServer( ('http://username.pythonanywhere.com/'), app_list)
try:
server.start()
except KeyboardInterrupt:
server.stop()
print "Server initiated..."
initiate()
print "Ended"
I created a "manual configuration" app on pythonanywhere.com.
Here's the configuration file (username_pythonanywhere_com_wsgi.py):
import sys
path = '/home/username/appname'
if path not in sys.path:
sys.path.append(path)
import deploy
deploy.initiate()
Now I'm pretty sure that it "almost worked", because in the server logs I could see my "Server initiated..." message.
2013-09-27 09:57:16 +0000 username.pythonanywhere.com - *** Operational MODE: single process ***
Server initiated...
Now the problem, when I try to view my app username.pyhtonanywhere.com/about, it times out.
This I believe is caused due to incorrect port given while starting the CherryPy server (in deploy.py).
Could anyone please tell how I can properly initiate the CherryPy server?
Joe Doherty is right. You want something more like this in you wsgi file:
import sys
sys.path = [ <path to your web app> ] + sys.path
from cherrypy._cpwsgi import CPWSGIApp
from cherrypy._cptree import Application
from <your_web_app> import <your web app class>
config_path = '<path to your cherrypy config>'
application = CPWSGIApp(
Application(<your web app class>(), '', config = config_path)
I stuck everything that should be based on your particular app in <>s.