How can I run a Flask app hosted on a2hosting? - python

I have just setup my first Flask project hosted on a server (a2hosting). Now, I want to run on the web application my python script (calculating a few things and then redirects to other url).
But I am not sure how do I set it up on my app server in a2hosting?
# A very simple Flask Hello World app for you to get started with...
from flask import Flask ,redirect
app = Flask(__name__)
#app.route('/set/<hana>')
def hello_world(hana):
import googlemaps
name = hana
return redirect('http://mycamp.co.il/yesh/'+name , code=302)
#app.route('/hello')
def hiii():
import pymongo
def insert(myreq):
dd={
"hihi":"yes1yes"
}
myreq.insert_one(dd)
return True
client = pymongo.MongoClient("mongodb://DETAILES.#routeplan-shard-00-00-d416l.gcp.mongodb.net:27017,routeplan-shard-00-01-d416l.gcp.mongodb.net:27017,routeplan-shard-00-02-d416l.gcp.mongodb.net:27017/test?ssl=true&replicaSet=routeplan-shard-0&authSource=admin&retryWrites=true")
mydb = client['router']
myplan = mydb['planner']
mydis = mydb['distance']
myopt = mydb['optimal']
myreq = mydb['request']
myus = mydb['user']
q=insert(myreq)
return 'helo world %s' + q
if __name__ == '__main__':
app.run(debug = True)

Related

dash within flask app from external folder

I have seen many discussions about running dash within flask but cannot make my own case to work.
I have ~4 pages in dash and now I would like to run them with flask (using an index file works just fine).
In this thread there is some code to tackle the issue
from dash import Dash,html
from werkzeug.middleware.dispatcher import DispatcherMiddleware
import flask
from werkzeug.serving import run_simple
import dash_html_components as html
server = flask.Flask(__name__)
dash_app1 = Dash(__name__, server=server, url_base_pathname='/dashboard')
dash_app2 = Dash(__name__, server=server, url_base_pathname='/reports')
dash_app1.layout = html.Div([html.H1('Hi there, I am app1 for dashboards')])
dash_app2.layout = html.Div([html.H1('Hi there, I am app2 for reports')])
#server.route('/')
#server.route('/hello')
def hello():
return 'hello world!'
#server.route('/dashboard/')
def render_dashboard():
return flask.redirect('/dash1')
#server.route('/reports/')
def render_reports():
return flask.redirect('/dash2')
app = DispatcherMiddleware(server, {
'/dash1': dash_app1.server,
'/dash2': dash_app2.server
})
run_simple('0.0.0.0', 8080, app, use_reloader=True, use_debugger=True)
And works, however when I am trying to import my own app it doesn't due to 404 not found. I can replicate the error easily by doing having the two dash apps in separate files like this
dummy/app1.py
from dash import Dash,html
import flask
server = flask.Flask(__name__)
dash_app1 = Dash(__name__, server=server, url_base_pathname='/dashboard/')
dash_app1.layout = html.Div([html.H1('Hi there, I am app1 for dashboards')])
dummy/app2.py
from dash import Dash,html
import flask
server = flask.Flask(__name__)
dash_app2 = Dash(__name__, server=server, url_base_pathname='/reports/')
dash_app2.layout = html.Div([html.H1('Hi there, I am app2 for reports')])
wsgi.py
from werkzeug.middleware.dispatcher import DispatcherMiddleware
import flask
from werkzeug.serving import run_simple
from dummy.app1 import dash_app1
from dummy.app2 import dash_app2
server = flask.Flask(__name__)
#server.route('/')
#server.route('/hello')
def hello():
return 'hello world!'
#server.route('/dashboard/')
def render_dashboard():
return flask.redirect('/dash1/')
#server.route('/reports/')
def render_reports():
return flask.redirect('/dash2/')
app = DispatcherMiddleware(server, {
'/dash1/': dash_app1.server,
'/dash2/': dash_app2.server
})
run_simple('0.0.0.0', 8080, app, use_reloader=True, use_debugger=True)
I tried moving the server.route within each dash app but without success. what am I missing?

Flask 404 error when initializing a connection with a react applicaiont

import os, re
from flask import Flask, send_from_directory, json,request
from flask_socketio import SocketIO
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
import random
app = Flask(__name__, static_folder='./build/static')
# Point SQLAlchemy to your Heroku database
uri = os.getenv("DATABASE_URL") # or other relevant config var
if uri and uri.startswith("postgres://"):
uri = uri.replace("postgres://", "postgresql://", 1)
app.config['SQLALCHEMY_DATABASE_URI'] = uri
# Gets rid of a warning
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
import models
cors = CORS(app, resources={r"/*": {"origins": "*"}})
socketio = SocketIO(
app,
cors_allowed_origins="*",
json=json,
manage_session=False
)
#app.route('/', defaults={"filename": "index.html"})
#app.route('/<path:filename>')
def index(filename):
return send_from_directory('./build', filename)
# When a client connects from this Socket connection, this function is run
#socketio.on('connect')
def on_connect():
print('User connected!')
# When a client disconnects from this Socket connection, this function is run
#socketio.on('disconnect')
def on_disconnect():
print('User disconnected!')
#socketio.on('index')
def on_index():
all_students = db.Students.query.all()
random1 = random.randint(0,models.Students.query().count())
random2 = random.randint(0,models.Students.query().count())
total_table = []
for student in all_students:
total_table.append(student)
firstStudent = []
secondStudent = []
while(random2 == random1):
random2 = random.randint(0,models.Students.query().count())
firstStudent.append(total_table[random1])
secondStudent.append(total_table[random2])
twoStudents = [firstStudent,secondStudent]
socketio.emit('students', {twoStudents:twoStudents})
# Note we need to add this line so we can import app in the python shell
if __name__ == "__main__":
# Note that we don't call app.run anymore. We call socketio.run with app arg
socketio.run(
app,
)
The react end of the application launches fine with no errors, and the database has no issues. I've used this skeleton for the base of a bunch of other projects and i've never had any issues. But for some reason i'm stuck at a brick wall setting this up. I know the issue is within the #app.route('/') part of the code. i've tried hard coding the html file into the url path, but that just causes other errors like missing 1 required positional argument: 'filename' flask. Any help is greatly appreciated
I tested your configuration and it doesn't give me any errors. Nevertheless I offer you an alternative solution.
You can provide the entire react build folder as a static folder. You can then deliver the "index.html" as a single file in the root route. The prerequisite is that the prefix for the static url path is empty.
# ...
app = Flask(__name__,
static_url_path='',
static_folder='./build'
)
# ...
#app.route('/')
def index():
return app.send_static_file('index.html')
# ...

Return continuous terminal log through flask client - Python

Is there a way to return multiple responses to 1 get request?
I have a basic flask app where I am trying to make it run another python app and send the terminal logs to the client side.
I can return a json value but I can't return any text or the output of the terminal.
Here is the server side:
from flask import Flask, stream_with_context, request, Response
from flask_restful import Api, Resource
from flask_socketio import SocketIO
import intermedia_choose_action_flask
import subprocess
app = Flask(__name__)
api = Api(app)
socketio = SocketIO(app)
class spamblacklistsend(Resource):
def get(self):
imapp = subprocess.Popen(["python3", "/home/tech/scripts/Intermedia_automate/intermedia_choose_action.py", "--addblockeveryone", "--ed", "test#fakeu.com"], bufsize=10, errors='replace')
imapp.app_context().push()
# p = subprocess.Popen(["python3", "/home/tech/scripts/Intermedia_automate/intermedia_choose_action.py", "--addblockeveryone", "--ed", "test#fakeu.com"], bufsize=10, errors='replace')
return imapp.app_context().push()
api.add_resource(spamblacklistsend, "/spamblacklistsend")
if __name__ == "__main__":
app.run(debug=True)
Here is the client side:
from flask import json
import requests
BASE = "http://127.0.0.1:5000/"
response = requests.get(BASE + "spamblacklistsend")
print(imapp.app_context().push())
I know that return stops the function. Is there anyway to return and continue?

Unable to see any message in website using flask

In my local host, I'm unable to see any message. I am using jupyter notebook.
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World"
if __name__ == "__main__":
app.debug = True
app.run(host='0.0.0.0',port=5005)

How do I mock PyMongo for testing with a Flask app?

I've found similar questions, but they seem to only cover mocking MongoDB and don't mention Flask.
I have a Flask app and I'm trying to unit test it with PyTest (including PyTest-Mongo and PyTest-Flask). However, before I can even get to the point of writing any tests, my test script crashes. The crash happens when importing the script with my Flash app: It's trying to create the PyMongo object without a url.
My question is: How can I ensure that PyMongo is mocked correctly at this point? According to the PyTest-Mongo documentation, the MongoDB test fixture should be passed to each of the test functions, but that doesn't help me if it's crashing on import.
test_app.py:
import pytest
import pytest_mongodb
from app import app
#pytest.fixture
def client():
app.config['TESTING'] = True
return client
app.py:
import ...
app = Flask(__name__)
app.config["MONGO_DBNAME"] = os.environ.get('DB_NAME')
app.config["MONGO_URI"] = os.environ.get('MONGO_URI')
app.secret_key = os.environ.get('SECRET')
mongo = PyMongo(app)
...
if __name__ == '__main__':
app.run(host=os.environ.get('IP'),
port=int(os.environ.get('PORT')),
debug=False)
we can wrap app and mongo in a function
This works because mongo is used as a local variable.
app.py
from flask import Flask
from flask_pymongo import PyMongo
def get_app_with_config(config):
app = Flask(__name__)
app.config.from_object(config)
mongo = PyMongo(app)
#app.route("/")
def index():
pass
.
.
return app, mongo
then we can create a test file and an application execution file with different databases:
test_app.py
from app import get_app_with_config
from config import TestConfig
app, mongo = get_app_with_config(TestConfig)
run.py
from app import get_app_with_config
from config import RunConfig
app, mongo = get_app_with_config(RunConfig)
if __name__ == '__main__':
app.run(port=8000)
Sample of config.py file:
class RunConfig:
MONGO_HOST = '192.168.1.37'
MONGO_PORT = 27017
MONGO_DBNAME = 'my_database'
MONGO_URI = f"mongodb://{MONGO_HOST}:{MONGO_PORT}/{MONGO_DBNAME}"
class TestConfig:
MONGO_HOST = '192.168.1.37'
MONGO_PORT = 27017
MONGO_DBNAME = 'my_database_test'
MONGO_URI = f"mongodb://{MONGO_HOST}:{MONGO_PORT}/{MONGO_DBNAME}"
TESTING = True
Needed a quick fix so I edited app.py so that it only hard-fails if PyMongo doesn't initialise when the file is executed (i.e. it ignores PyMongo's failed initialisation when running unit-tests.)
app = Flask(__name__)
app.config["MONGO_DBNAME"] = os.environ.get('DB_NAME')
app.config["MONGO_URI"] = os.environ.get('MONGO_URI')
app.secret_key = os.environ.get('SECRET')
try:
mongodb = PyMongo(app).db
except ValueError:
"""We don't provide a URI when running unit tests, so PyMongo will fail to initialize.
This is okay because we replace it with a version for testing anyway. """
print('PyMongo not initialized!')
mongodb = None
.
.
.
if __name__ == '__main__':
if not mongodb:
print('Cannot run. PyMongo failed to initialize. Double check environment variables.')
exit(1)
app.run(host=os.environ.get('IP'),
port=int(os.environ.get('PORT')),
debug=False)
In my tests file, I just assign the mocked mongoDB client to the app in the tests that need it. Definitely not the ideal solution.
def test_redacted(client, mongodb):
app.mongodb = mongodb
...

Categories