Im stuck in deploying my working Django Application on a production PLESK server.
The project can be started as a development server successfully by typing:
httpdocs# cd mysite
httpdocs/mysite# source myvenv/bin/activate
httpdocs/mysite# export LD_LIBRARY_PATH="/usr/local/lib"
httpdocs/mysite# python manage.py runserver <freyt.de>:8000
Then, if I point the browser to freyt.de:8000 I can see my app. Fine.
Right now, I'm trying to call my app by Passenger from Apache. When checking with "passenger-config restart-app" it seems to run, but when curl freyt.de it shows me html with 403 Forbidden. So, I assume my Django app is not started successfully.
This is my current folder structure:
I already adjusted some topics in PLESK as follows:
Apache Webserver: wsgi is activated
I created a Service Plan and subscribed it with my domain freyt.de
In the Service Plan under tab "Webserver" I added additional directives for HTTP as follows.
PassengerEnabled On
PassengerAppType wsgi
PassengerStartupFile passenger_wsgi.py
In the Service Plan under "Hosting Parameters" I enabled SSH access to the server shell: /bin/bash
For the "Domain" I set the Document root to "..httpdocs/public". Also I added in "Apache & nginx Settings" the same directives. (I also tried without, but dont seem to have an effect.)
Some details at Document Root:
I added .htaccess in public with again same directives (just for testing). No other files in public.
My passenger_wsgi.py contains, which seems to be ok:
import sys, os
cwd = os.getcwd()
sys.path.append(cwd)
sys.path.append(cwd + '/mysite')
if sys.version < "2.7.9":
os.execl(cwd + "/mysite/myvenv/bin/python", "python3.6", *sys.argv)
sys.path.insert(0, cwd + '/mysite/myvenv/bin')
sys.path.insert(0, cwd + '/mysite/myvenv/lib/python3.6')
#sys.path.insert(0, cwd + '/mysite/myvenv/lib/python3.6/site-packages/django')
sys.path.insert(0, cwd + '/mysite/myvenv/lib/python3.6/site-packages')
os.environ['DJANGO_SETTINGS_MODULE'] = "mysite.settings"
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
The file mysite/mysite/wsgi.py is untouched:
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
application = get_wsgi_application()
Would be great, if someone could point me in the correct direction. I think its just a small mistake somewhere :-) Thanks in advance.
Related
I have seen that gunicorn reload uses inotify (when installed, which I have). I have verified that the reloader is working, and that some file changes are detected (mainly, changes to gunicorn itself)
But my application code is not included in the list of files being supervised by inotify.
What can I do for gunicorn to supervise my application code?
My application is a django app, with the following wsgi.py:
"""
WSGI config for my project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
import sys
from django.core.wsgi import get_wsgi_application
# This allows easy placement of apps within the interior
# core directory.
app_path = os.path.abspath(os.path.join(
os.path.dirname(os.path.abspath(__file__)), os.pardir))
sys.path.append(os.path.join(app_path, 'core'))
# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi daemon mode with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.production"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
I'm trying to deploy a web app built with Django/Redux/React/Webpack on a Digital Ocean droplet. I'm using Phusion Passenger and Nginx on the deployment server.
I used create-react-app to build a Django app which has a frontend that uses React/Redux, and a backend api that uses django-rest-framework. I built the frontend using npm run build.
The Django app is configured to look in the frontend/build folder for its files and everything works as expected, including authentication. It's based on this tutorial: http://v1k45.com/blog/modern-django-part-1-setting-up-django-and-react/
In settings.py:
ALLOWED_HOSTS = ['*']
TEMPLATES = [
...
'DIRS': [
os.path.join(BASE_DIR, 'frontend/build'),
],
...
]
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'frontend/build/static'),
]
On my development machine, I activate a Python 3.6 virtual environment and run ./manage.py runserver, and the app is displayed at localhost:3000.
On the deployment server, I've cloned the files into a folder in var/www/ and built the frontend.
I've set up Passenger according to the docs with a file passenger_wsgi.py:
import myapp.wsgi
application = myapp.wsgi.application
And the wsgi.py file is in the djangoapp folder below:
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings')
application = get_wsgi_application()
The Passenger docs only cover a single-part app:
https://www.phusionpassenger.com/library/walkthroughs/start/python.html
https://www.phusionpassenger.com/library/walkthroughs/deploy/python/digital_ocean/nginx/oss/xenial/deploy_app.html
https://www.phusionpassenger.com/library/deploy/wsgi_spec.html
I've tried cloning the tutorial part 1 code directly onto my server and following the instructions to run it. I got this to work on the server by adding "proxy": "http://localhost:8000" to frontend/package.json. If I run the Django server with ./manage.py runserver --settings=ponynote.production_settings xxx.x.x.x:8000
then the app is correctly served up at myserver:8000. However Passenger is still not serving up the right files.
I have changed wsgi.py to say this:
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.production_settings")
application = get_wsgi_application()
The page served by Passenger at URL root now appears to have the right links to the js files such as "text/javascript" src="/static/bundles/js/main.a416835a.js, but the links don't work: the expected js is not present. Passenger is failing to serve the js files from static/bundles/js, even though the Django server can find them.
Very grateful for any help or ideas.
Create-react-app has a fairly opinionated setup for local and production environments.
Locally, running npm start will run a webpack-dev-server, which you would typically access on port 3000. It runs a local nodejs web server to serve the files. You can route requests to your local Django server via the proxy setting.
It's worth noting that at this point there is little or no connection between your React app and Django. If you use the proxy setting, the only thing connecting the two apps is the routing of any requests not handled by your React app to your Django app via the port.
By default in create-react-app (and as noted in the tutorial you mentioned you are following) in production you would run npm run build which will process your create-react-app files into static JS and CSS files, which are then accessed in Django like static files any other Django app.
One thing Django is missing in order to access the static files is a way to know what files are generated when running npm run build. Running a build will typically result in files output like this:
- css
|- main.e0c3cfcb.css
|- main.e0c3cfcb.css.map
- js
|- 0.eb5a2873.chunk.js
|- 0.eb5a2873.chunk.js.map
|- 1.951bae33.chunk.js
|- 1.951bae33.chunk.js.map
A random hash is added to filenames to ensure cache busting. This is where webpack-bundle-tracker and django-webpack-loader come in. When build files are generated, an accompanying file is also created called manifest.json, listing the files created for the build. This is generated in Webpack and picked up by django-webpack-loader so that Django can know which files to import.
It is possible to run a nodejs server in production, or to use server-side rendering, but if you're following the tutorial you mentioned and using create-react-app default settings, then running npm run build and deploying the static files is the simplest, safest option.
Nothing in any of the Passenger deployment links you mention cover anything beyond deploying a Python/Django app - you would need to manage two apps and deployments to have both Django and React running as servers in production.
Note that the tutorial you mention covers how to get your build files into Django in production, but you will need to ensure that you have webpack-bundle-tracker, django-webpack-loader and your Django staticfiles configuration all configured to work together.
The key missing setting was the 'location' setting in the Passenger config file.
Although the Django server serves up the static files, including the build files for your React app, Nginx doesn't see any static files except those in a 'public' directory.
So to deploy a Django app built with Webpack to production, you need to tell Nginx about those files. If you're using Passenger, these settings are probably in a separate Passenger config file. 'alias' is the command to use in this case where the folder has a different name from 'static' (which is where the web page links point).
If you use a virtual environment for your app, you need to specify where Passenger can find the right Python executable.
/etc/nginx/sites-enabled/myapp.conf
server {
listen 80;
server_name xx.xx.xx.xx;
# Tell Passenger where the Python executable is
passenger_python /var/www/myapp/venv36/bin/python3.6;
# Tell Nginx and Passenger where your app's 'public' directory is
# And where to find wsgi.py file
root /var/www/myapp/myapp/myapp;
# Tell Nginx where Webpack puts the bundle folder
location /static/ {
autoindex on;
alias /var/www/myapp/myapp/assets/;
}
# Turn on Passenger
passenger_enabled on;
}
Passenger uses the wsgi.py file as an entry point to your app. You need a passenger_wsgi.py file one level above the wsgi.py file. This tells Passenger where to find the wsgi.py file.
/var/www/myapp/myapp/passenger_wsgi.py
import myapp.wsgi
application = myapp.wsgi.application
/var/www/myapp/myapp/myapp/wsgi.py
If you are using a separate production_settings.py file, make sure this is specified here.
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.production_settings")
application = get_wsgi_application()
Where should the DJANGO_SETTINGS_MODULE environment variable be set?
Multiple possible locations:
In a config file (.ebextensions) as follows:
option_settings: aws:elasticbeanstalk:application:environment:
DJANGO_SETTINGS_MODULE: "app.settings"
In the wsgi.py file before application is loaded
In manage.py (I also see this on different Django projects on the web)
If I don't specify it in wsgi.py, it looks like it can't be found at all. Therefore, I wonder if the environment variables set in .ebextensions are set before wsgi.py is loaded.
Any idea?
Introduce your wsgi.py in a config file in .ebextensions
django_aws_eb.config:
option_settings:
aws:elasticbeanstalk:container:python:
WSGIPath: "my_site/wsgi.py"
Specifly your DJANGO_SETTING_MODULE in your `wsgi.py' file
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_site.settings")
application = get_wsgi_application()
aws beanstalk first looks for configs in .ebextension to then locate wsgi.py to then locate settings.
more info: Configure Your Django Application for Elastic Beanstalk
I am trying to deploy a simple flask application in the Apache shared hosting server.
I am not sure what is wrong here.
I am stuck at the .cgi file for now.
The flask app - hello.py:
#!/usr/bin/python
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!\n"
if __name__ == "__main__":
app.run()
The myapp.cgi file:
#!/usr/bin/python
import os
from wsgiref.handlers import CGIHandler
from hello import app
os.environ['SERVER_NAME'] = '127.0.0.1'
os.environ['SERVER_PORT'] = '5000'
os.environ['REQUEST_METHOD'] = 'GET'
os.environ['PATH_INFO'] = ""
CGIHandler().run(app)
Both the files are placed in the /home/username/public_html/cgi-bin directory
The same cgi-bin has the directory named myenv - it's a virtualenv I have created. The virtualenv is active.
Now,
I navigate to the cgi-bin directory and run -
python hello.py
I get this :
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
So this is fine. Now I am running the myapp.cgi file:
python myapp.cgi
I get this :
Status: 301 MOVED PERMANENTLY
Content-Type: text/html; charset=utf-8
Content-Length: 251
Location: http://127.0.0.1:5000/
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>Redirecting...</title>
<h1>Redirecting...</h1>
<p>You should be redirected automatically to target URL: http://127.0.0.1:5000/. If not click the link.
How can I make this status as 200 OK,
Please suggest.
Thanks!
I had to make few changes in the .cgi file. Below is the final file.
import os
from wsgiref.handlers import CGIHandler
from hello import app
CGIHandler().run(app)
and added these lines in my hello.py file:
import os
import sys
sys.path.insert(0, '/home/username/public_html/cgi-bin/myenv/lib/python2.6/site-packages')
Refer this - https://medium.com/#mohdejazsiddiqui/deploy-flask-app-in-apache-shared-hosting-5b3c82c8fd5e
I think you have 2 big misunderstandings about how apache works with flask with the help of cgi.
Apache uses the system directorys for the python interpreter. You can in fact change the sys.path Like here descriped. But that is far from ideal.
you don't have to call python for your cgi file. The Server will do that when you did your config correctly
in the cgi doc of flask are some ways how you get the server to work with the cgi file.
Since you say you want it to upload at shared hosting writing a .htaccess file for your needs would be the most promesing way, since most of those services only allow you to work from your public dircectory. In this case you also have to use a shared hoster where python is on the server or be willed to install python with all the packages you need for you, since you can't install any packages by yourself.
You could try the changing of the interpreter path, but i have no experience if that would work on shared hosting.
I've built a Django project that works, even after I freeze it using Cx_Freeze and Py2exe.
Now I'm trying to set up the project for distribution, which requires a real webserver. I'm going for Gunicorn (will add Nginx once it works). I managed to run the Gunicorn server properly through the command line using :
gunicorn wsgi:application
However, I need to be able to run the server from my Python script, as the server is ment to be localhost. Gunicorn used to be shipped with a command 'run_gunicorn' designed for Django, but this command is now deprecated.
I tried understanding the following method :
How to use Flask-Script and Gunicorn
But I can't figure out how to make it work with Django.
The following doesn't work:
from django.core.wsgi import get_wsgi_application
from gunicorn.app.base import Application
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
application = get_wsgi_application()
Application().run(application)
Could someone tell me how to start the gunicorn server from my Python script ?