Serving static files through apache - python

I am new to the whole mod_wsgi and serving files through apache. I am really comfortable with flask but this is something i can't get my head around. I did the hello-world program and successfully displayed hello world!
Now i wanted to display a image file. So I updated my hello-world.py to:
from flask import *
yourflaskapp = Flask(__name__)
#yourflaskapp.route("/")
def hello():
file="203.jpg"
return render_template("hello.html",file=file)
# return"HEY"
if __name__ == "__main__":
yourflaskapp.run()
my directory structure is something like:/var/www/hello-world
/hello-world
test.py
yourflaskapp.wsgi
/static
-203.jpg
/templates
-hello.html
My template is simple:
<!DOCTYPE html>
<html><head><title>hi</title></head>
<body>
<img src="{{url_for('static',filename=file)}}"/>
</body></html>
and my apache conf file is:
<VirtualHost *:80>
WSGIDaemonProcess yourflaskapp
WSGIScriptAlias / /var/www/hello-world/yourflaskapp.wsgi
Alias /static/ /var/www/hello-world/static
Alias /templates/ /var/www/hello-world/templates
<Directory /var/www/hello-world>
WSGIProcessGroup yourflaskapp
WSGIApplicationGroup %{GLOBAL}
Order deny,allow
Allow from all
</Directory>
<Directory /var/www/hello-world/static>
Order allow,deny
Allow from all
</Directory>
<Directory /var/www/hello-world/templates>
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
Though when i open the browser and head to my ip, it doesn't show the image file.
What am i doing wrong? Is there any other approach i should follow?
and if anyone could recommend any good links from where i can understand working with flask+mod_wsgi+apache2

It is generally always a good idea to have trailing slash balanced when mounting static files at a sub URL. So instead of:
Alias /static/ /var/www/hello-world/static
use:
Alias /static /var/www/hello-world/static

Related

Can I create a flask webapp in the same url with other pages(like wordpress)?

I have a self-hosted server, only for my lan, with a Wordpress(miservidor.com) and Owncloud(miservidor.com/owncloud) page, those pages work perfectly, and i recentlly decided to create a webapp with flask under the same domain like miservidor.com/musicdownloader. I have tried to make it works but with no results, my config files are these:
/etc/apache2/sites-available/000-default.conf
<VirtualHost *:80>
ServerName miservidor.com
Redirect / https://miservidor.com/
</VirtualHost>
/etc/apache2/sites-available/default-ssl.conf
<IfModule mod_ssl.c>
<VirtualHost _default_:443>
ServerAdmin webmaster#localhost
DocumentRoot /var/www/html
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
SSLEngine on
SSLCertificateFile /etc/ssl/certs/apache-selfsigned.crt
SSLCertificateKeyFile /etc/ssl/private/apache-selfsigned.key
<FilesMatch "\.(cgi|shtml|phtml|php)$">
SSLOptions +StdEnvVars
</FilesMatch>
<Directory /usr/lib/cgi-bin>
SSLOptions +StdEnvVars
</Directory>
<Directory />
AllowOverride ALL
</Directory>
</VirtualHost>
</IfModule>
/etc/apache2/config-available/musicdownloader.conf
<VirtualHost *:80>
WSGIScriptAlias /musicdownloader /var/www/musicdownloader/musicdownloader.wsgi
<Directory /var/www/musicdownloader/musicdownloader/>
Order allow,deny
Allow from all
</Directory>
Alias /musicdownloader/static /var/www/musicdownloader/musicdownloader/static
<Directory /var/www/musicdownloader/musicdownloader/static/>
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
/etc/apache2/config-available/owncloud.conf
Alias /owncloud "/var/www/owncloud/"
<Directory /var/www/owncloud/>
Options +FollowSymlinks
AllowOverride All
<IfModule mod_dav.c>
Dav off
</IfModule>
SetEnv HOME /var/www/owncloud
SetEnv HTTP_HOME /var/www/owncloud
</Directory>
My web app hierarchy is (in /var/www/):
|--musicdownloader/
|----musicdownloader.wgsi
|----musicdownloader/
|------app.py
|------static/
|--------main.css
|------templates/
|--------musicdownloader.html
|--------download.html
musicdownloader.wgsi
#!/usr/bin/python
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/musicdownloader/")
from musicdownloader import app as application
app.py
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route('/musicdownloader', methods=["POST","GET"])
def musicdownloader():
return render_template('musicdownloader.html')
if __name__ == "__main__":
app.run()
Is this the correct way to do it? It is better to use subdomains or different domains with the same ip? Thanks in advance.
I found the solution, I can do it by changing the content I put in the file /etc/apache2/config-available/musicdownloader.conf to:
WSGIScriptAlias /musicdownloader /var/www/musicdownloader/musicdownloader.wgsi
WSGIDaemonProcess musicdownloader python-path=/var/www/musicdownloader:/var/www/musicdownloader/musicdownloader/venv/lib/python3.8/site-packages
WSGIProcessGroup musicdownloader
<Directory /var/www/musicdownloader/musicdownloader/>
Require all granted
</Directory>
Alias /musicdownloader/static /var/www/musicdownloader/musicdownloader/static
<Directory /var/www/musicdownloader/musicdownloader/static/>
Require all granted
</Directory>
Then:
sudo systemctl reload apache2
And now I can have my flask app in:
miservidor.com/musicdownloader

Serve one flask app at root and another at a different path with apache2 and mod_wsgi

I am trying to serve one flask app directly at localhost, and another at localhost/menus.
When my apache configuration is like this:
<VirtualHost *:80>
ServerName localhost
# logs configuration -------------------------------------------------
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
# front page ---------------------------------------------------------
WSGIDaemonProcess flask_ac user=#1000 group=#1000 threads=5
WSGIScriptAlias /front /var/www/flask_ac/hookup.wsgi
<Directory /var/www/flask_ac>
WSGIProcessGroup flask_ac
WSGIApplicationGroup flask_ac
Require all granted
</Directory>
# start menus --------------------------------------------------------
WSGIDaemonProcess menus user=#1000 group=#1000 threads=5
WSGIScriptAlias /menus /var/www/flask_ac/projects/menus/hookup.wsgi
<Directory "/var/www/flask_ac/projects/menus/">
WSGIProcessGroup menus
WSGIApplicationGroup menus
Require all granted
</Directory>
It works fine, but it is serving the first app at localhost/front instead of just localhost.
If I change my first WSGIScriptAlias to:
WSGIScriptAlias / /var/www/flask_ac/hookup.wsgi
It will serve the first app correctly at localhost, but the second app at localhost/menus breaks, and returns not found.
I found this answer about a similar issue, but it doesn't address this directly, and I cant seem to figure it out.
Change the order such that the application for the sub URL is first.
WSGIScriptAlias /menus /var/www/flask_ac/projects/menus/hookup.wsgi
...
WSGIScriptAlias / /var/www/flask_ac/hookup.wsgi
Documentation mentioning ordering at:
http://modwsgi.readthedocs.io/en/develop/user-guides/configuration-guidelines.html#the-wsgiscriptalias-directive

Apache2 host, url not served with mod_wsgi

Just stated to host a website with Django, the problem is like this.
I put an html file for testing under /usr/local/django/virenv/Personal/mysite.com/, which is also the Document root in 000-default.conf, that page can be access via mysite.com
Then I started a django project and an app, in the app/view.py I put
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, a django view.")
In the app/urls.py I put
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^index$', views.index, name = 'index'),
]
added the following to project/urls.py
urlpattrens = [
url(r'^home/', include('app.urls')),
# below is admin url created with startproject
url(r'^admin/', admin.site.urls)),
]
lastly I turn DEBUT=False in project/settings.py, and added ip to ALLOWED_HOSTS
After python manage.py runserver ip:8080 , ip:8080/home/index, and ip:8080/admin are all available.
Next I tried restart apache2, went to mysite.com/admin and mysite.com/home/index
both got
404
Not Found The requested URL /admin was not found on this server.
I guess the mod_wsgi is not working.
The httpd.conf looks like
LoadModule wsgi_module modules/mod_wsgi.so
WSGIScriptAlias / /usr/local/django/virenv/Personal/mysite.com/project/wsgi.py process-group=mysite.com
WSGIPythonHome /usr/local/django/virenv
WSGIDaemonProcess mysite.com python-home=/usr/local/django/virenv python-path=/usr/local/django/virenv/Personal/mysite.com
WSGIProcessGroup mysite.com
WSGIApplicationGroup %{GLOBAL}
<Directory /usr/local/django/virenv/Personal/mysite.com/project>
<Files wsgi.py>
Order allow,deny
Allow from all
Require all granted
</Files>
</Directory>
<Directory /usr/local/django/virenv/Personal/mysite.com/>
Order allow,deny
Allow from all
Require all granted
Options -Indexes +FollowSymLinks -Includes
</Directory>
000-default.conf looks like
<VirtualHost *:80>
ServerAdmin webmaster#localhost
DocumentRoot /usr/local/django/virenv/Personal/mysite.com
<Directory /usr/local/django/virenv/Personal/mysite.com>
AllowOverride All
Options +FollowSymLinks
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
I use ubuntu 16 lts with apache2.4, django 1.10
every directory and file along this path
/usr/local/django/virenv/Personal/mysite.com/*
is set to chmod a+x and chmod a+r
Any guesses or solution?
EDIT: by the way, in wsgi.py
import os
import sys # added from other stack overflow answers
import django.core.handlers.wsgi as WSGIhand # added from other posts
os.environ.["DJANGO_SETTINGS_MODULE"] = "project.settings"
application = WSGIhand.WSGIHandler()

Flask routing throw 404 on production server

on my production server, my flask application throw 404 when i tried to access www.example.com/admin however, if i tried to access root content, everything works fine. I am using apache for my web server with python 3.4
#app.route('/')
def index():
return render_template("search.html")
. python functions in between
.
.
.
#app.route("/admin")
def admin():
return render_template("adminAuth.html", error=False)
#app.route("/admin", methods=["POST"])
def adminAuth():
# Intentionally return None
return None
Remarks: On my test environment, (PyCharm with Flask) everything works fine, I can access /admin
This is my WSGI conf
<VirtualHost *:80>
ServerName NAME
ServerAdmin admin#mywebsite.com
WSGIScriptAlias / /path/to/app.wsgi
<Directory /path/to/webapp/>
Order allow,deny
Allow from all
</Directory>
Alias /static /path/to/webapp/static
<Directory /path/to/webapp/static/>
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/path/to/error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/path/to/access.log combined
</VirtualHost>

Apache, Web.py and Mod_WSGI Issue - Page Not Found

Please your help to know what is wrong with my configuration Apache + Web.py + Mod_WSGI and my website cannot be loaded, this is my config:
Apache version: 2.7.4
Web.py version -> https://github.com/webpy/webpy
mod_wsgi -> not sure if 3.3 or 3.4
Directory
/var/www/pyapps/bot
web -> link webpy
webpy
code.py
static
templates
Apache
ServerAdmin webmaster#localhost
DocumentRoot /var/www
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
CustomLog ${APACHE_LOG_DIR}/access.log combine
WSGIScriptAlias /sitea /var/www/pyapps/bot/code.py/
Alias /sitea/static /var/www/pyapps/bot/static
Alias /sitea/templates /var/www/pyapps/bot/templates
AddType text/html .py
<Directory /var/www/pyapps/bot>
Order deny,allow
Allow from All
</Directory>
<Directory /sitea/static>
Options +Indexes
</Directory>
Code.py
import web
urls = (
'/.*', 'hello',
)
class hello:
def GET(self):
return "Hello, world."
application = web.application(urls, globals()).wsgifunc()
Result
Not Found
The requested URL /sitea was not found on this server.
Apache/2.2.22 (Ubuntu) Server at xxx.xxx.xxx.xxx Port 80
You shouldn't have a trailing slash on the end of the WSGIScriptAlias path:
WSGIScriptAlias /sitea /var/www/pyapps/bot/code.py
Also note you shouldn't really have your WSGI application files inside the document root (/var/www). Put them somewhere else (and change the WSGIScriptAlias path accordingly).

Categories

Resources