Setup flask up on cpanel Error: We're sorry, but something went wrong. The issue has been logged for investigation. Please try again later - flask

Here is the problem. I have uploaded the files and created the app. But after modifying the passenger_wsgi.py file and refreshing the app, this error page is shown: We're sorry, but something went wrong. The issue has been logged for investigation. Please try again later.
Here is the directory structure:
Home/user/myproject/
*****************/main/
*****************/auth/
*****************/aritcles/
*****************/errors/
*****************/static/
*****************/templates/
*****************/users/
****************/__init__.py
****************/passenger_wsgi.py
*********/public_html
*********************/.htaccess
__init__.py file:
from flask import Flask, request, session, current_app
from flask_sqlalchemy import SQLAlchemy
from .config import config
from flask_login import LoginManager, current_user
db = SQLAlchemy()
login_manager = LoginManager()
# login route end_points
login_manager.login_view = 'auth.login'
def create_app(config_name=config['production']):
app = Flask(__name__)
app.config.from_object(config_name)
db.init_app(app)
login_manager.init_app(app)
from .main import main
from .auth import auth
from .users import users
from .errors import errors
from .articles import articles
app.register_blueprint(main, url_prefix='')
app.register_blueprint(auth, url_prefix='/auth')
app.register_blueprint(errors, url_prefix='/errors')
app.register_blueprint(users, url_prefix='/users')
app.register_blueprint(articles, url_prefix='/articles')
return app
passenger_wsgi.py file:
import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
from myproject import create_app
application = create_app()
Auto generated .htacces file:
# DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION BEGIN
PassengerAppRoot "/home/user/myproject"
PassengerBaseURI "/"
PassengerPython "/home/user/virtualenv/myproject/3.9/bin/python"
# DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION END
# DO NOT REMOVE OR MODIFY. CLOUDLINUX ENV VARS CONFIGURATION BEGIN
<IfModule Litespeed>
SetEnv TWILIO_ACCOUNT_SID *************************
SetEnv TWILIO_AUTH_APP_TOKEN qydYjO9wKRdG7cMEe***************
SetEnv TWILIO_AUTH_TOKEN e8964a3d51627e4*******************
SetEnv TWILIO_PHONE_NUMBER +1**********
</IfModule>
# DO NOT REMOVE OR MODIFY. CLOUDLINUX ENV VARS CONFIGURATION END
Project creation configuration:
python version: 3.9.12
application root: project
application url: mydomaine
Then, I added for environment variables and install all required packages.
I still can't figure out what's wrong. I would be grateful for any help. Thanks in advance.
I tried these links: [https://stackoverflow.com/questions/75116826/deploying-simple-flask-app-on- shared-hosting-using-cpanel-but-only-root-url-can], [https://stackoverflow.com/questions/63106913/python-flask-app-routing-in-cpanel-can-only-access-root-url/63971427?newreg=aacb5dd4e5ad448cb94a35e97192ce4b]

Related

How to determine flask_app name

Sorry if this is a bit basic but wanted to validate what my flask_app name would be that I set in my .env file when running locally.
I run my app using a wsgi.py file in root with the following contents:
from app import create_app, db
application = create_app()
if __name__ == '__main__':
application.run()
However I then have a app/init.py
import os
from config import Config
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
#not sure if i mucked this up
db.init_app(app)
from app.main import main_blueprint
app.register_blueprint(main_blueprint)
return app
Which I run with flask run. Therefore is my app name “app” or “application” or even something else?
You want flask_app variable to be the name of the file which runs the app, so for you in your .env file it looks like you should have:
FLASK_APP = run.py
where run.py is the name of the file containing the first block of code in your question, assuming that your .env file is also in your root folder, let me know if that helps.

URL Handler not working in Goole app engine and flask Application

I'm here to ask a silly question, unfortunately I can't figure out with it.
I have a Google app Engine project developed with Flask web framework.
The structure of my project is like that (in uppercase are the directories, while in lowercase the files):
> -PROJECT DIR
> -APP
> -API
> -HANDLERS
> home.py
> -TEMPLATES
> home.html
- flask_app.py
> app.yaml
> appengine.config.pu
In home.py I am just rendering /TEMPLATES/home.html
from flask import render_template
from app.flask_app import app
#app.route('/')
def home():
return render_template('home.html')
This is the structure of app.yaml files:
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /.*
script: app.flask_app.app
When i start to debugging and try to access localhost at http://127.0.0.1:8080/ instead of rendering the templates it appears to me the following error Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
Is that something wrong with app.yaml file? I think it is all correct, even the url.
EDIT
flask_app.py
import appengine_config
import logging
from app import app_secret_key
from flask import Flask
from flask_wtf.csrf import CSRFProtect
app = Flask(__name__)
app.config.from_object(__name__)
CSRF_PROTECT = CSRFProtect(app)
if appengine_config.GAE_DEV:
logging.warning('Using a dummy secret key')
app.secret_key = 'my_dummy_secret_key'
app.debug = True
else:
app.secret_key = app_secret_key.secret_key
You forgot import HANDLERS.home at the end of flask_app.py
This is required on your application, Flask need to know which files register views or route.

setting up Django app to work on google app engine GAE (app.yaml & main.py)

I have a working Django app that I was able to get functioning on Heroku. The structure is project named 'untitled' and an app named 'web' such that the structure is:
project_root
static
templates
untitled
--->init.py
--->settings.py
--->urls.py
--->wsgi.py
web
--->init.py
--->admin.py
--->apps.py
--->models.py
--->tests.py
--->urls.py
--->views.py
This is a fairly basic app that I can get working outside of GAE (local and on Heroku), however, I'm getting stuck on the app.yaml and main.py requirements for GAE.
My app.yaml is:
application: seismic-interpretation-institute-py27
version: 1
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /.*
script: main.app
libraries:
- name: django
version: "latest"
and my main.py (generated from PyCharm) is
import os,sys
import django.core.handlers.wsgi
import django.core.signals
import django.db
import django.dispatch.dispatcher
# Google App Engine imports.
from google.appengine.ext.webapp import util
# Force Django to reload its settings.
from django.conf import settings
settings._target = None
os.environ['DJANGO_SETTINGS_MODULE'] = 'untitled.settings'
# Unregister the rollback event handler.
django.dispatch.dispatcher.disconnect(
django.db._rollback_on_exception,
django.core.signals.got_request_exception)
def main():
# Create a Django application for WSGI.
application = django.core.handlers.wsgi.WSGIHandler()
# Run the WSGI CGI handler with that application.
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
Finally, the output that is reported when running locally is
It seems that the error,
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
is causing my problems. I am not exactly sure how to fix it.
try replace
from django.conf import settings
settings._target = None
os.environ['DJANGO_SETTINGS_MODULE'] = 'untitled.settings'
to
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "untitled.settings")
from django.conf import settings
settings._target = None

How do I get django to execute a remote celery task? Seems to ignore BROKER_URL in settings.py

I've got a django app that's trying to call a celery task that will eventually be executed on some remote hosts. The task codebase is completely separate to the django project, so I'm using celery.execute.send_task and calling it from a post_delete model signal. The code looks a bit like this:
class MyModel(models.Model):
#staticmethod
def do_async_thing(sender, instance, **kwargs):
celery.execute.send_task("tasks.do_my_thing", args=[instance.name])
signals.post_delete.connect(MyModel.do_async_thing, sender=MyModel)
I'm using the latest Django (1.6.1) and celery 3.1.7, so I understand that I don't need any extra module or app in my django project for it to be able to talk to celery. I've set BROKER_URL inside my settings.py to be the right url amqp://user:password#host/vhost.
When this method fires, I get a Connection Refused error. There's no indication on the celery broker that any connection was attempted - I guess it's not seeing the BROKER_URL configuration and is trying to connect to localhost.
How do I make this work? What extra configuration does send_task need to know where the broker is?
So I discovered the answer, and it was to do with not reading the tutorial (http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html) closely enough.
Specifically, I had the correct celery.py in place which I would have thought should have loaded the settings, but I'd missed the necessary changes to __init__.py in the django project, which wasn't hooking everything together.
My celery.py should be:
from __future__ import absolute_import
import os
from celery import Celery
from django.conf import settings
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
app = Celery('mypoject')
# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
and the __init__.py should be simply:
from __future__ import absolute_import
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app

flask - easy application but with error 404 not found

I am starting with flask, I went through many tutorials and everything worked. But I started my own application and I get only error 404 not found.
Configuration of my apache virtual server is:
<VirtualHost domain:80>
ServerAdmin webmaster#domain
ServerName domain
ServerAlias domain *.domain
WSGIDaemonProcess test user=www-data group=www-data threads=5 home=/var/www-py/domain
WSGIScriptAlias / /var/www-py/domain/domain.wsgi
<Directory /var/www-py/domain>
WSGIProcessGroup test
WSGIApplicationGroup %{GLOBAL}
WSGIScriptReloading On
Order deny,allow
Allow from all
</Directory>
</VirtualHost>
domain.wsgi:
import sys, os
current_dir = os.path.abspath(os.path.dirname(__file__))
sys.path.append(current_dir)
from domain import app as application
domain/__init__.py
import os, sys
from flask import Flask
from datetime import *
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.debug=True
app.secret_key = 'mysecretkey'
db = SQLAlchemy(app)
domain/views/index.py
# -*- coding: utf-8 -*-
from flask import Flask, request, session, g, redirect, url_for, \
abort, render_template, flash
#app.route('/')
def index():
return render_template('index.html')
That's all and easy application. Problem is that all applications which I tried was written in one file. Now I am trying to separated to classify it into files to be easier to manage bigger project.
Please could you help me.
Thank you.
You have two problems:
In views/index.py you don't actually define app, so that will result in a NameError if you ever actually import views.index.
In __init__.py you never import views.index so your route never gets added to the Flask.url_routes map.
You have two options:
You can take the circular imports way out, as specified in the docs:
# views.index
from flask import render_template
from domain import app
#app.route("/")
def index():
return render_template("index.html")
# __init__.py
# ... snip ...
db = SQLAlchemy(app)
# View imports need to be at the bottom
# to ensure that we don't run into problems
# with partially constructed dependencies
# as this is a circular import
# (__init__ imports views.index which imports __init__ which imports views.index ...)
from views import index
You can pull the creation of app into a separate file and avoid circular imports entirely:
# NEW: infrastructure.py
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask("domain")
db = SQLAlchemy(app)
# views.index
from domain.infrastructure import app
# NEW: app.py
from domain.infrastructure import app
import domain.views.index
# __init__.py
# is now empty
You need import views.index in domain/init.py, and add "from domain import app" in index.py. Otherwise it cannot find app