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

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

Related

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

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]

No module named 'django' when trying to import Django into Scrapy

This is my folder structure:
root:
|--Django_project
|--|-- db_app
|--|-- Django_project
|--|-- manage.py
|--Scrapy_project
|--|--Scrapy_project
|--|--|--spiders
|--|--|--settings.py
|--|--|--pipelines.py
|--|--|--items.py
|--|--|--middlewares.py
|--|--scrapy.cfg
In settings.py I have this:
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath('.')))
os.environ['DJANGO_SETTINGS_MODULE'] = 'Django_project.settings'
import django
django.setup()
I've tried every possible path, including an absolute path to the project root, to the Django project, to the Django app - nothing works and I get this:
ModuleNotFoundError: No module named 'django'
Thanks for the help!
EDIT:
I should probably clarify that I'm running in a virtual environment.

django standalone script: cannot import name 'Celery' from 'celery'

I am trying to run a standalone Django scipt
import os, sys, django
proj_path = "/path/to/django-project"
import ipdb; ipdb.set_trace()
# This is so Django knows where to find stuff.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "boiler.settings")
sys.path.append(proj_path)
django.setup()
When i run It says
ImportError: cannot import name 'Celery' from 'celery' (/path/to/django-poject/boiler/celery.py)
My folder structure:
django-poject
-- boiler
-- __init__.py
-- settings.py
-- celery.py
-- manage.py
__init__.py
from .celery import app as celery_app
__all__ = ['celery_app']
celery.py
import os
from celery import Celery
import django
import sys
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'boiler.settings')
#This defines the celery app instance
redis = 'redis://:pass#localhost:6379/0'
app = Celery(dirname,
broker=redis,
backend=redis
)
I am able to run celery using
activate virtualenv
cd to django-poject
celery -A boiler worker --loglevel=debug
without any problems
But in standalone its creating problems
You have to name your celery.py something else. Like django_celery.py otherwise it won't work. Celery works fine without it that way, but you want to integrate in with django and like what Santhosh said, the absolute import of itself is giving you issues.
In your project's __init__.py you'll need something like:
from __future__ import absolute_import, unicode_literals
from your_path_to.django_celery import app as celery_app
__all__ = ('celery_app',)

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.

Django version in GAE

I'm tring to use Django 1.1 in GAE, But when I uncomment
use_library('django', '1.1')
in this script
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from google.appengine.dist import use_library
#use_library('django', '1.1')
# 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
import django.core.handlers.wsgi
import django.core.signals
import django.db
import django.dispatch.dispatcher
# 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()
I receives
AttributeError: 'module' object has no
attribute 'disconnect'
What is going on?
From http://justinlilly.com/blog/2009/feb/06/django-app-engine-doc-fix/
For those setting up Django on Google
App Engine on version after the
signals refactor, the following fix is
needed for the code supplied by
Google.
# Log errors.
django.dispatch.dispatcher.connect(
log_exception, django.core.signals.got_request_exception)
# Unregister the rollback event handler.
django.dispatch.dispatcher.disconnect(
django.db._rollback_on_exception,
django.core.signals.got_request_exception)
becomes:
# Log errors.
django.dispatch.Signal.connect(
django.core.signals.got_request_exception, log_exception)
# Unregister the rollback event handler.
django.dispatch.Signal.disconnect(
django.core.signals.got_request_exception,
django.db._rollback_on_exception)