How to run a function before rendering the Template? - html

I have a chat room socket program and I am trying to make a web view for that by FLASK. The server is running at the background and the client would connect to that server when the user submitted his name by a HTML form.
So, I have this code in my app.py file. I can see that the client successfully connected in the Python terminal but the template won't render any more.
from flask import Flask
from flask import render_template , request
import client
app = Flask(__name__)
#app.route('/indexchat.html',methods=['POST'])
def chatroom():
a = request.form.get('name')
b=[]
if a:
b.append(a)
client.startclient(a)
return render_template("indexchat.html",args=b)
if __name__ == '__main__':
app.run()
If I remove the client.startclient(a) function the page will render.

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.

"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

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)

Service Account and PyDrive

I would like to use the Google Drive API to store some backups on it using a cronjob. I just don't understand how I can use PyDrive using a Service Account. When I generate the service account file, and I put it in the directory as my script as client_secret.json.
Using this code :
#!/usr/bin/env python
# -*- coding: utf8 -*-
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
def main():
gauth = GoogleAuth()
drive = GoogleDrive(gauth)
f = drive.CreateFile({'parent': 'toto'})
f.SetContentFile('test.drive.py')
f.Upload()
if __name__ == '__main__':
main(sys.argv[1:])
Result
pydrive.settings.InvalidConfigError: Invalid client secrets file Invalid file format.
Well ok. Then I look at other posts on SO, and find these two :
Automate Verification Process
The code from the first answer on this question returns this :
Traceback (most recent call last):
File "test.drive.py", line 4, in <module>
from oauth2client.client import SignedJwtAssertionCredentials
ImportError: cannot import name SignedJwtAssertionCredentials
And then this one :
Automating pydrive verification process
Which just... Doesn't help me much.
Where should I start ? What should I do ? Could someone give me an example with pydrive and Service Authentication just to upload a file ?
EDIT :
After some more research it seems like I needed to install pycrypto to fix the import error described above. I don't know why as it is not specified in the error message.
After some more research it seems like I needed to install pycrypto to fix the import error described above. I don't know why as it is not specified in the error message.

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

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. :)