Changes to Flask index.py not loading - python

I'm working on a pretty simple web application utilizing Flask, and I'm trying to deploy it to a Digital Ocean VPS. I have it running with apache2 and WSGI. Here's the git repo. I am terrible at devops, so I don't know why this isn't working.
In /var/www/VAWomensHealth/ I have a folder with the flask app called VAWomensHealth and a VAWomensHealth.wsgi file that looks like this:
#!/usr/bin/python
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/VAWomensHealth/")
from VAWomensHealth import app as application
#from app import app as application
application.secret_key = 'Add your secret key'
My index.py file looks like this:
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/feeds')
def feeds():
return render_template('feeds.html')
if __name__ == '__main__':
app.run(debug=True)
and my VAWomensHealth.conf inside /etc/apache2/sites-enabled/ looks like this:
<VirtualHost *:80>
ServerName bagbot.com
ServerAdmin chris#example.com
WSGIScriptAlias / /var/www/VAWomensHealth/VAWomensHealth.wsgi
WSGIScriptReloading On
<Directory /var/www/VAWomensHealth/VAWomensHealth/>
Order allow,deny
Allow from all
</Directory>
Alias /static /var/www/VAWomensHealth/VAWomensHealth/static
<Directory /var/www/VAWomensHealth/VAWomensHealth/static/>
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
So when I go to the domain, the main site loads. And when I edit my static files or templates, those changes are immediately reflected on the domain.
However, code changes that I make to index.py don't seem to be taking effect (such as trying to have the index file load a different template). This is preventing me from adding other routes to my app.
Any ideas?

As for me (but I can't test it) you have to change name index.py to __init__.py
Or you have to use index in wsgi file
from VAWomensHealth.index import app as application

Related

Django: Can't access static files in python script

I have deployed a django project with mod wsgi on an apache server. Everything works so far.
In one python script I'd like to open a file in static files.
Therefore I have tried something like this:
mycode.py
import cv2
class Foo():
def __init__(self):
...
def openImg(self):
self.myimg = cv2.imread('static/myapp/img/picture.jpg',0)
return self.myimg
.. just for testing
However it can't find this file. 
Whether in path ('static/myapp/img/picture.jpg'), nor path ('myapp/static/myapp/img/picture.jpg') nor in path ('../static/myapp/img/picture.jpg') and some other which I have already forgot.
It always returns "None".
If I try the same on my "undeployed" local project it works without any problem. 
I have already collected all staticfiles to /myproject/static and given enough rights to access them. 
By the way, the access to the static files in the html works in production.
What's the problem?
Can you give me any advice?
Thank you.
Some additional information:
views.py
from django.shortcuts import render
from .mycode import Foo
def index(request):
# New Instance for class Foo
bar = Foo()
# Return img array to put it in html for whatever
imagearray = bar.openImg()
context = {'imgarray': imgarray}
return render(request, 'myapp/index.html', context)
Thats an example of my directory
/home/myuser/MyProject
/static/myapp/img/picture.jpg (collected)
/
/myapp
/static/myapp/img/picture.jpg
/mycode.py
/views.py
/MyProject
/settings.py
In my apache config file:
Alias /static /home/myuser/MyProject/static
<Directory /home/myuser/MyProject/static>
Require all granted
</Directory>
Alias /media /home/myuser/MyProject/media
<Directory /home/myuser/MyProject/media>
Require all granted
</Directory>
<Directory /home/myuser/MyProject/MyProject>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
WSGIScriptAlias / /home/myuser/MyProject/MyProject/wsgi.py
WSGIDaemonProcess django_app python-path=/home/myuser/MyProject python-home=/home/myuser/MyProject/venv
WSGIProcessGroup django_app
In mycode.py you might want to try:
from django.contrib.staticfiles.storage import staticfiles_storage
import cv2
class Foo():
def __init__(self):
...
def openImg(self):
path = staticfiles_storage.path('myapp/img/picture.jpg')
self.myimg = cv2.imread(path,0)
return self.myimg
This was happening to me until i ran
python manage.py collectstatic
could you try this?

404 Not Found when deploying Flask on WSGI

I've been using Flask for a while for development but recently decided to address the "This server should not be used for production" warning. I've spent several hours trying to get wsgi to work to no avail.
Here's the structure of my /var/www:
webApp
webApp
static
templates
__init__.py
webapp.wsgi
My webapp.wsgi file:
#!/usr/bin/python3
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/webApp/")
from webApp import app as application
application.secret_key = 'Add your secret key'
My webApp.conf file:
<VirtualHost *:80>
ServerName my_vps_ip
ServerAdmin email#mywebsite.com
WSGIScriptAlias / /var/www/webApp/webapp.wsgi
<Directory /var/www/webApp/webApp/>
Order allow,deny
Allow from all
</Directory>
Alias /static /var/www/webApp/webApp/static
<Directory /var/www/webApp/webApp/static/>
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
And finally, my __init__.py file:
from flask import Flask
app = Flask(__name__)
#app.route('/', methods = ['GET'])
def test():
return 'test'
if __name__ == '__main__':
app.run()
And this happens when I visit the server ip:
Why could this be happening? I've spent all day trying to figure this out, so any help is appreciated!
Can You please check the serverName is correct and should be a registered domain.

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>

Serving static files through apache

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

Categories

Resources