How can I call a Django app from another Python app? - python

In the standard setup, Django applications are called by a WSGI server (like gunicorn and mod_wsgi) to answer HTTP requests, the entrypoint at user-level is the django View.
Can I make a custom entrypoint to call Django apps? If so, How I properly load a Django app?
Edit: Looking at the entrypoint in the wsgi.py file made by the startproject command, I see that 1) it sets the DJANGO_SETTINGS_MODULE var and calls get_wsgi_application which 2) calls django.setup() and 3) returns a WSGI application that will be called by the WSGI Server. 1 and 2 also happens when django's admin commands are ran. Is it enough to do 1 and 2 and have a properly loaded Django app? At 3 the django's middlewares are loaded, but they are not compatible, since I will not be doing HTTP calls (but the Django app will, of course, answer HTTP requests coming from other clients).

Is it enough to do 1 and 2 and have a properly loaded Django app?
Looking at Django's source code and this documentation, I figured out how to load a Django app. Taking as example the Django's intro tutorial, I could load the polls app and call its index view this way:
# Let Django knows where the project's settings is.
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
from django.apps import apps
# Load the needed apps
apps.populate(installed_apps=['polls.apps.PollsConfig'])
# Make sure the above apps were loaded
apps.check_apps_ready()
apps.check_models_ready()
# Call it
from polls.views import index
# Here index view is decoupled from Django's HTTP interface, so in polls/views.py you have:
# def index():
# return Question.objects.order_by('-pub_date')[:5]
print('index view: ' + str(index()))
It does not load any of the Django middlewares (they are coupled to the HTTP interface). The polls app does not depends on other installed apps, otherwise all dependencies should be loaded too.

Related

Setting up Flask-Admin and Flask-Security

I have a Flask-Admin project set up with Flask-Security as well. It is pretty much https://pythonhosted.org/Flask-Security/quickstart.html#id1 but just more advanced. I can access the login page at localhost/login and logout and localhost/logout. The logging in and logging out works.
The templates for Flask-Admin works and everything is displayed as I'd expect. However, there are no templates on my machine or docker container where the Flask-Admin app is run. I installed Flask by running pip install Flask-Admin. I know I can over ride the security log in by adding something like
SECURITY_LOGIN_USER_TEMPLATE = 'security/login_user.html'
to the config file and uploading to /templates/security/login_user.html. There is also using
{%extends base.html}
to have a common theme. Should I have template files already in my project?
Flask Security have a default login template, if you want to use your own template for login or register follow these steps:
Create in template folder the a subfolder named security
Add your html documents to this folder
Go to your flask configuration and add the following settings:
If your want the register functionality
SECURITY_REGISTERABLE = True
Add the name of your templates:
SECURITY_LOGIN_USER_TEMPLATE = 'security/login.html'
SECURITY_REGISTER_USER_TEMPLATE = 'security/register.html'
Remember to use the appropriate form in login.html and in register.html, usually causes doubts but is simple:
register.html: register_user_form.field
login.html: login_user_form.field
These are the configurations for this work correctly.
this repository can you to see and understand better doubt:

Integrate AdminLTE to django project

I want to integrate AdmineLTE to my django project, with the help of its
README file.
https://github.com/StephenPCG/django-adminlte-templates
I followed all steps required in the file, but when I'm running my app, and want to login, I'm getting the following error.
You're using the staticfiles app without having set the required STATIC_URL setting.
which come from here
django-adminlte-templates/AdminLTE/templatetags/AdminLTE.py in <module>
bootstrap_url_base = _bootstrap_url_base if _bootstrap_url_base else static('bootstrap')

how a django reusable apps can initialize itself?

I'm creating a django app as a python package , almost similar to django-tinymce
interesting point about django-tinymce is that every time I restart my web server , for example I run :
python manage.py runserver
somehow automatically a settings.py file inside django-tinymce start running.
how is this possible ?
I just add tinymce in the INSTALLED_APPS and nothing else but the code inside python2.7/site-packages/tinymce/settings.py starts running and do a few initialization operations every time I restart my web server or run any manage.py command.
Such initialisation code is often put in the models.py which is run by Django at start or restart.
In this example app it is just a matter of imports run - models.py imports widgets and widgets import settings.
As django 1.7 each app can contain an app.py file to do any initialization it needs to do.
Imagine we have a app called profile.In your app directory create an apps.py like this :
#apps.py
from django.apps import AppConfig
class ProfileConfig(AppConfig):
name = "profiles"
verbose_name = 'User Profiles'
def ready(self):
#do what ever you want
One more step to complete this behavior is to specify default_app_config
Which should happened in init.py of your app :
# profile/__init__.py
default_app_config = 'profile.apps.ProfileConfig'
This behavior can be used in many usecases including : changing project settings,registering signal handlers
More details can be found in Django 1.7 release notes and Django docs:Applications

How to make python on Heroku https only?

I have python/django app on Heroku (Cedar stack) and would like to make it accessible over https only. I have enabled the "ssl piggyback"-option, and can connect to it via https.
But what is the best way to disable http access, or redirect to https?
Combining the answer from #CraigKerstiens and #allanlei into something I have tested, and verified to work. Heroku sets the HTTP_X_FORWARDED_PROTO to https when request is ssl, and we can use this to check:
from django.conf import settings
from django.http import HttpResponseRedirect
class SSLMiddleware(object):
def process_request(self, request):
if not any([settings.DEBUG, request.is_secure(), request.META.get("HTTP_X_FORWARDED_PROTO", "") == 'https']):
url = request.build_absolute_uri(request.get_full_path())
secure_url = url.replace("http://", "https://")
return HttpResponseRedirect(secure_url)
Django 1.8 will have core support for non-HTTPS redirect (integrated from django-secure):
SECURE_SSL_REDIRECT = True # [1]
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
In order for SECURE_SSL_REDIRECT to be handled you have to use the SecurityMiddleware:
MIDDLEWARE = [
...
'django.middleware.security.SecurityMiddleware',
]
[1] https://docs.djangoproject.com/en/1.8/ref/settings/#secure-ssl-redirect
Not sure if #CraigKerstiens's answer takes into account that request.is_secure() always returns False if behind Heroku's reverse proxy and not "fixed". If I remember correctly, this will cause a HTTP redirect loop.
If you are running Django with gunicorn, another way to do it is to add the following to gunicorn's config
secure_scheme_headers = {
'X-FORWARDED-PROTO': 'https'
}
Run with some like this in your Procfile
web: python manage.py run_gunicorn -b 0.0.0.0:$PORT -c config/gunicorn.conf
By setting gunicorn's secure-scheme-header, request.is_secure() will properly return True on https requests. See Gunicorn Config.
Now #CraigKerstiens's middleware will work properly, including any calls to request.is_secure() in your app.
Note: Django also has the same config setting call SECURE_PROXY_SSL_HEADER, buts in the dev version.
What framework are you using for your application? If you're using Django you could simple use some middleware similar to:
import re
from django.conf import settings
from django.core import urlresolvers
from django.http import HttpResponse, HttpResponseRedirect
class SSLMiddleware(object):
def process_request(self, request):
if not any([settings.DEBUG, request.is_secure()]):
url = request.build_absolute_uri(request.get_full_path())
secure_url = url.replace("http://", "https://")
return HttpResponseRedirect(secure_url)
2020 update:
If you are using Flask, I would recommend the following:
#app.before_request
def before_request():
if 'DYNO' in os.environ:
if request.url.startswith('http://'):
url = request.url.replace('http://', 'https://', 1)
code = 301
return redirect(url, code=code)
The above works excellent on Heroku and allows you to use http in local development with heroku local.
Flask-SSLify is no longer maintained and no longer officially supported by the Flask community.
2014 original answer:
If you're using Flask, this works quite well:
Do "pip install flask-sslify"
(github is here: https://github.com/kennethreitz/flask-sslify)
Include the following lines:
from flask_sslify import SSLify
if 'DYNO' in os.environ: # only trigger SSLify if the app is running
on Heroku
sslify = SSLify(app)
For Flask use Talisman. Flask, Heroku and SSLify documentations favor the use of Talisman over SSLify because the later is no longer maintained.
From SSLify:
The extension is no longer maintained, prefer using Flask-Talisman as
it is encouraged by the Flask Security Guide.
Install via pip:
$ pip install flask-talisman
Instatiate the extension (example):
from flask import Flask
from flask_talisman import Talisman
app = Flask(__name__)
if 'DYNO' in os.environ:
Talisman(app)
Talisman enables CSP (Content Security Policy) by default only allowing resources from the same domain to be loaded. If you want to disable it and deal with the implications:
Talisman(app, content_security_policy=None)
If you don't want to disable it you have to set the content_security_policy argument to allow resources from external domains, like CDNs, for instance. For that refer to the documentation.

How to avoid NotImplementedError "Only tempfile.TemporaryFile is available for use" in django on Google App Engine?

I'm using Django 1.1 on Google App Engine through use_library. No Django GAE helper, Django non-rel or similar tools are used here. Django handles URLs routing, forms validation etc., but I'm using pure App Engine models.
In one of my Django forms there is a FileField, which from time to time, seems to call django.core.files.uploadedfile.TemporaryUploadedFile. This class then uses tempfile.NamedTemporaryFile and this results in App Engine raising:
File "/base/python_runtime/python_dist/lib/python2.5/tempfile.py", line 45, in PlaceHolder
raise NotImplementedError("Only tempfile.TemporaryFile is available for use")
Trying to solve this problem I took uploadedfile module from Google App Engine Helper for Django (which doesn't use NamedTemporaryFile) saved it as gae_uploadedfile.py in application directory and in my _djangomain.py_ file I added:
from google.appengine.dist import use_library
use_library('django', '1.1')
(...)
import gae_uploadedfile
django.core.files.uploadedfile = gae_uploadedfile
djangomain.py is a file where i redirect all urls - in app.yaml I have:
- url: /.*
script: djangomain.py
But it didn't help, I still get this exception. What am I doing wrong, is there other solution to avoid this error while using FileField from django.forms?
You need to update the settings.py file with the following to change the default Django behaviour:
# only use the memory file uploader, do not use the file system - not able to do so on
# google app engine
FILE_UPLOAD_HANDLERS = ('django.core.files.uploadhandler.MemoryFileUploadHandler',)
FILE_UPLOAD_MAX_MEMORY_SIZE = 2621440 # the django default: 2.5MB
More info here:FILE_UPLOAD_MAX_MEMORY_SIZE and
upload-handlers
If you are uploading images you will be restricted by the 1MB quotas for image transformation etc.. Quotas_and_Limits

Categories

Resources