OPENSHIFT - 'wsgi.py' does not contain WSGI application 'application' - openshift

I am trying to start a new python3.3 app on Openshift. Due to the changes they made a couple of weeks ago I am having trouble getting the new app started. I copied a known working app into a new Openshift app. I am now getting this error:
Target WSGI script '/var/lib/openshift/<masked>/app-root/runtime/repo/wsgi.py' does not contain WSGI application 'application'.
My wsgi.py code is the same in both working and non working apps
import os
from myapp import main_production_no_pserve
if __name__ == '__main__':
ip = os.environ['OPENSHIFT_PYTHON_IP']
port = int(os.environ['OPENSHIFT_PYTHON_PORT'])
app = main_production_no_pserve(global_config=None)
from waitress import serve
print("Starting Waitress Server on http://{0}:{1}".format(ip, port))
serve(app, host=ip, port=port, threads=50)
The working app was created before the mid March Openshift change. Something is different now that the exact same code does not work.
It seems openshift is looking for an application function entry point within the wsgi.py. In the old method of the working app, the wsgi.py is actually executed (not looking for the application function. For kicks, I did this based off of the default wsgi.py when new openshift app was created.
import os
from myapp import main_production_no_pserve
def application(environ, start_response):
ip = os.environ['OPENSHIFT_PYTHON_IP']
port = int(os.environ['OPENSHIFT_PYTHON_PORT'])
app = main_production_no_pserve(global_config=None)
from waitress import serve
print("Starting Waitress Server on http://{0}:{1}".format(ip, port))
serve(app, host=ip, port=port, threads=50)
return
With that change I get the dreaded OSError: [Errno 98] Address already in use and a rhc app-force-stop does nothing.
I am at a loss why one app works and another does not. I would appreciate some help. :)

Related

Flask Application (MySQL) - KeyError: 'migrate'

In order to perform a migration, through commands flask db init and flask db migrate, I receive the following error: directory = current_app.extensions['migrate'].directory KeyError: 'migrate'.
I have created a Migrate object within my __init__.py file, however, still receive the error stated above:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from config import app_config
from flask_login import LoginManager
from flask_migrate import Migrate
# Creating Flask app.
app = Flask(__name__)
# Database variable initialisation.
db = SQLAlchemy()
login_manager = LoginManager()
def create_app(config_name):
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(app_config[config_name])
app.config.from_pyfile('config.py')
db.init_app(app)
# Creating login manager object and initialising it.
# Login view and message prevent a user to accessing a page they are not authorised to.
login_manager.init_app(app)
login_manager.login_message = "Please login to access this page."
login_manager.login_view = "auth.login"
migrate = Migrate(app, db)
from app import models
return app
Any advice for what I am doing wrong? I have already viewed quite a few pages related to this error and have implemented the possible alterations.
I found the problem. The above __init__.py class was completely fine.
My config.py file which contained the following code:
SQLALCHEMY_DATABASE_URI = 'mysql+mysqlconnector://{db_user}:{my_password}#localhost/{database}'
... had a format extension to it which was not needed. I have successfully updated my database.

Apache2 No permission to write file [Errno 13] Permission denied Flask Python

A few Details first
So I did a little web application with Flask.
In theory it should get the ip whenever someone requests or visits the website.
I have everything done (On Windows my Code runs perfectly), but I installed Flask and moved my Project over to a Linux Server where I have Apache2 installed. Ive configured Apache so it handles the requests for the Flask web app.
Everything fine, like my templates load just fine, but the part with logging the ip doesn't work.
I think getting the IP is no problem, tho storing it in say a json file is.
Every time i try to run I get a 500 error on my website.
Apache Error Log : [Errno 13] Permission denied '/opt/iplogs/iplog.json'
The Python Code
def writeToJSONFile(path, fileName, data):
filePathNameWExt = path + fileName + '.json'
with open(filePathNameWExt, 'a') as fp:
json.dump(data, fp, indent=2)
fp.close()
#app.route("/")
def getIP():
visit = {}
ip_visit = request.remote_addr
now = datetime.now()
request_time = now.strftime("%d/%m/%Y %H:%M:%S")
visit["IP"] = str(ip_visit)
visit["date"] = str(request_time)
writeToJSONFile("/opt/iplogs/", "iplog", visit) # WHEN i comment this function out there is no 500 error
return render_template("home.html")
The Main Problem
So in Windows in a Development Envoirement it works fine, but also in linux when i just let Flask run without apache handling its requests
Only when I run the website through Apache I get the error "Permission denied"
So it has to do something with apache and its permissions to write?
Note the folder where my flask(python code) lives is completly different from where the ips are logged
+ I use Ubuntu and i didn't change anything regarding permissions with files or so, heck im even running through root (I know I shouldn't be doing that but its only for testing a very small project)
Thats all I can give you guys
Thanks for all the responses
Try this:
sudo chown -R www-data:www-data /opt/iplogs/
The Apache2 user www-data has no perrmission to manipulate this file.

"from flaskext.mysql import MySQL" causes server to show 502 bad gateway

new to python. Following a couple tutorials to serve an application (ddworkflow.com) using Python 3.6.7, Flask, Gunicorn, NGINX, and MySQL on Ubuntu 18.04
The tutorials are:
https://philchen.com/2019/02/11/how-to-make-a-python-web-app-in-virtualenv-using-flask-gunicorn-nginx-on-ubuntu-18-04
and
https://code.tutsplus.com/tutorials/creating-a-web-app-from-scratch-using-python-flask-and-mysql--cms-22972
I got through the first tutorial and am able to successfully serve the basic web pages from the second tutorial.
Installing everything in a virtual environment and just installed flask-mysql using pip install flask-mysql.
My pip freeze shows:
Click==7.0
Flask==1.0.2
Flask-MySQL==1.4.0
itsdangerous==1.1.0
Jinja2==2.10
MarkupSafe==1.1.0
PyMySQL==0.9.3
Werkzeug==0.14.1
After installing Flask-MySQL I tested the installation by trying the following different variations of the "from" command (at the python prompt):
from flask.ext.mysql import MySQL
from flaskext.mysql import MySQL
from flask_mysql import MySQL
from flaskext.mysql import MySQL
1, 2, and 3 all produce ModuleNotFoundError... The only one that does not throw an error is from flaskext.mysql import MySQL
However, when I add from flaskext.mysql import MySQL to my flask app file (app01.py) I immediately get a 502 bad gateway error. My app01.py file is
from flask import Flask, render_template, json, request
#from flaskext.mysql import MySQL #<--comment out or get 502 error
hello = Flask(__name__)
#hello.route("/")
def greeting():
return render_template('index.html')
#hello.route('/showSignUp')
def showSignUp():
return render_template('signup.html')
#hello.route('/signUp',methods=['POST'])
def signUp():
# read the posted values from the UI
_name = request.form['inputName']
_email = request.form['inputEmail']
_password = request.form['inputPassword']
# validate the received values
if _name and _email and _password:
return json.dumps({'html':'<span>All fields good !!</span>'})
else:
return json.dumps({'html':'<span>Enter the required fields</span>'})
if __name__ == "__main__":
hello.run(host='0.0.0.0')
Any help getting the 502 error to go away so that I connect to the database is much appreciated. Thank you.
This could be a virtualenv error, check out this link: https://www.pythonanywhere.com/forums/topic/2877/
Very similar question from earlier: ImportError: No module named flask.ext.mysql

Keycloak authentication with Electron App

Hi I've been stuck on this for days! I'm trying to use keycloak to authenticate my electron app after converting my react app using this guide.
When I run 'npm run electron:dev' , keycloak redirects to the login page. However, when I run 'npm run electron:prod' this fails.
Logs from keycloak server shows:
Server:server-one] 08:58:31,575 WARN [org.keycloak.events] (default task-3) type=LOGIN_ERROR, realmId=codingpedia, clientId=my-ui, userId=null, ipAddress=127.0.0.1, error=invalid_redirect_uri, redirect_uri=file:///home/mycompany/john/projects/boilerplate-javascript-electron/app/build/index.html
Notice that the redirect_uri is 'file:///...' which I believe to be the cause of it.
I've also tried to change the below but it does not resolve the problem.
// import createHistory from 'history/createBrowserHistory';
import createHistory from 'history/createHashHistory';
Why is this working in dev but not in prod? Is there something I'm missing? Thank you in advance!
It works in dev probably because the "index.html" file is located in your computer (file:///home/mycompany/john/projects/boilerplate-javascript-electron/app/build/index.html).
This stackoverflow thread tells how to properly set the redirect_uri parameter, through the admin console.
Note: make sure you can remotely access your index.html in prod, using a browser or any other client tool (HTTP GET).

web2py function not triggered on user request

Using web2py (Version 2.8.2-stable+timestamp.2013.11.28.13.54.07), on 64-bit Windows, I have the following problem
There is an exe program that is started on user request (first an txt file is created then p is triggered).
p = subprocess.Popen(['woshi_engine.exe', scriptId], shell=True, stdout = subprocess.PIPE, cwd=path_1)
while the exe file is running it is creating a txt file.
The program is stopped on user request by deleting the file the program needs as input.
when exe is started i have other requests user can trigger. it is common that request comes to server (I used microsoft network monitor to check that), but the function is not triggered.
I tried using scheduler but no success. Same problem
I am really stuck here with this problem
Thank you for your help
With a help of web2py google group the solution is.
I used scheduler. Created a scheduler.py file with the following code
def runWoshiEngine(scriptId, path):
import os, sys
import time
import subprocess
p = subprocess.Popen(['woshi_engine.exe', scriptId], shell=True, stdout = subprocess.PIPE, cwd=path)
return dict(status = 1)
from gluon.scheduler import Scheduler
scheduler = Scheduler(db)
In my controller function
task = scheduler.queue_task(runWoshiEngine, [scriptId, path])
you also have to import scheduler (from gluon.scheduler import Scheduler)
then I run the scheduler from command prompt with the following (so if I understood correctly you have two instances of web2py running, one for webserver, one for scheduler)
web2py.py -K woshiweb -D 0 (-D 0 is for verbose logging so it can be removed)