Deploying Flask Rest API using Shared Hosting - python

I'm having trouble deploying my REST API and keep getting a 500 Internal Server Error. I've gone through several possible solutions and guides to fix this problem, including those below:
http://flask.pocoo.org/docs/0.10/deploying/cgi/
Deploy flask application on 1&1 shared hosting (with CGI)
and was following this guide:
http://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask
Here is my code:
restapplication.py
#!/home/myusername/public_html/todo-api/flask/bin/python
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return "Hello, World!"
run.cgi
#!/home/myusername/public_html/todo-api/flask/bin/python
import cgitb; cgitb.enable()
from wsgiref.handlers import CGIHandler
from restapplication import app
CGIHandler().run(app)
.htaccess (stored at /home/myusername/public_html/)
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /home/myusername/public_html/todo-api/flask/run.cgi/$1 [L]
I appreciate all the help I can get.

Not sure if you got the solution, but for records-
if you have your virtual environment set, then you will have to add these lines in your restapplication.py to point to the site-packages, so that your code can access Flask library.
import os
import sys
sys.path.insert(0, '/home/username/public_html/cgi-bin/myenv/lib/python2.6/site-packages')
Rest everything looks okay.
Maybe you can check the file permissions of the .cgi file and .py file. The file permissions should be 755.
refer : http://www.comfycoder.com/home/how_to_deploy_a_flask_app_in_apache_shared_hosting

Related

Running flask and python with CGI

I registered a domain and it allows the use of CGI scripts. But I don't know how to run flask + python with the script.
https://flask.palletsprojects.com/en/1.1.x/deploying/cgi/ gives a decent description of what to do but still was unable to get flask and python to run. My python file:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return '<h1>Hello World!</h1>'
Also the cgi file:
#!/usr/bin/python
from wsgiref.handlers import CGIHandler
from yourapplication import app
CGIHandler().run(app)
And the htaccess file:
DirectoryIndex Home.html
# Begin EnforceSSL double-numbersign-freelancer.com
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www.)?double-numbersign-freelancer.com$
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L]
</IfModule>
# End EnforceSSL
Okay. I checked it
Answering for my configuration → CentOS 7 / httpd 2.4.6
Open /etc/httpd/conf/httpd.conf and add python handler
# standard part
<Directory "/var/www/cgi-bin">
AllowOverride None
Options None
Require all granted
# add handler here
AddHandler cgi-script .py
</Directory>
Put run.py inside /var/www/cgi-bin
#!/usr/bin/python3
from wsgiref.handlers import CGIHandler
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return '<h1>Hello World!</h1>'
#app.route('/suburl')
def index2():
return '<h1>Hello World 2!</h1>'
CGIHandler().run(app)
Change script permissions to allow execution:
chmod +x /var/www/cgi-bin/run.py
Now you can access:
http://your_server_url.com/cgi-bin/run.py → Hello World!
http://your_server_url.com/cgi-bin/run.py/suburl → Hello World 2!
Huh. That was my first experience with Flask CGI. Pretty simple and good for small or test projects.
Anyway I recommend to use gunicorn, uwsgi or mod_wsgi for apache in production.
EDIT1: Using CGI without flask
Actually you don't need flask for run CGI scripts. It can be written with any language that can read environment variables and output some data.
Bash example /var/www/cgi-bin/run.cgi:
#!/usr/bin/bash
echo "Content-type:text/plain"
echo
echo -e "HELLO WORLD\nYour URL path is $PATH_INFO"
Output will be:
http://example.com/cgi-bin/run.cgi/suburl
HELLO WORLD
Your URL path is /suburl

flask: The requested URL was not found on this server

I'm working with a shared hosting account which uses apache 2.4 , trying to deploy a flask app using http://fgimian.github.io/blog/2014/02/14/serving-a-python-flask-website-on-hostmonster . I've put the code and the fcgi script in public_html folder The contents of the folder are in the screenshot above:
The manage_apache.fcgi script is:
#!/home/username/anaconda2/bin/python
import sys,os
from flup.server.fcgi import WSGIServer
sys.path.insert(0, '/home/username/public_html')
from myflaskapp.settings import Config, SharedConfig
from myflaskapp.app import create_app
if __name__ == '__main__':
app = create_app(SharedConfig)
WSGIServer(app).run()
I've gotten to the last step and while testing it at the command line using putty to SSH in:
[~/public_html]# ./manage_apache.fcgi
I can see the correct web page being generated, so I assume that fast cgi is supported by my host. I'm not getting any python errors.
The .htaccess file out of the article is :
AddHandler fcgid-script .fcgi
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ manage_apache.fcgi/$1 [QSA,L]
In the browser when I surf to mysite.org I am getting
Not Found
The requested URL /manage_apache.fcgi/ was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
according to support The .htaccess file is redirecting to manage_apache.fcgi/$1
-rwxr-xr-x 1 myusername myusername Nov 22 17:26 manage_apache.fcgi*
How can I fix this?
I suspect
sys.path.insert(0, '/home/username/public_html')
is an absolute path, but flask application is looking to a relative path respect to flask gateway, and cannot find it.
Have you tried to wrap the libraries in the app instance - move the absolute path in the app instance?
As an example, see http://werkzeug.pocoo.org/:
from werkzeug.wrappers import Request, Response
#Request.application
def application(request):
return Response('Hello World!')
if __name__ == '__main__':
from werkzeug.serving import run_simple
# move absolute path here
run_simple('localhost', 4000, application)
I suspect that fcgi is not supported on that host. Just because a host lets you run a Python script on the command line does not mean that they have configured mod_fcgi in Apache.
Try this: apachectl -t -D DUMP_MODULES | grep cgi. You should see fcgi_module or fastcgi_module, or possibly a cgi_module.
If you only see a cgi_module, then you should be able to use AddHandler cgi-script .py instead of AddHandler fcgid-script .fcgi.
If you see none of those, then you can try wsgi: apachectl -t -D DUMP_MODULES | grep wsgi. If you see wsgi_module, then you know you can use wsgi. At that point, you might be able to follow instructions here under .htaccess.

Still having issues deploying flask app on Godaddy shared hosting

I've been trying now for some time to deploy my flask app on a Godaddy hosting server. I have done extensive searches online and followed them but I'm still having issues. Right now my app is just displaying as ordinary html so I'm having things like {{my_var}} displayed on the page. My flask app works locally and this is the folder structure;
myApp folder, which contains static folder for css,javascript, and images, templates folder for my html, and the myapp.py and forms.py files come under the myApp folder
On my hosting server my folder structure is currently this; $HOME/public_html which contains the index.html and base.html (index.html inherits from this file for the header and footers), $HOME/public_html/cgi-bin which contains myapp.cgi, myapp.py, and .htaccess files.
I've created a cgi file and made it executable which is saved in the public_html/cgi-bin folder. The file is also made executable with 755 permission. These are the contents;
#!/home/username/public_html/cgi-bin/flask_app/bin/python
from wsgiref.handlers import CGIHandler
from myapp import app
import os
import cgitb; cgitb.enable()
os.environ["SERVER_NAME"] = "127.0.0.1"
os.environ["SERVER_PORT"] = "4000"
os.environ["REQUEST_METHOD"] = "GET"
os.environ["SERVER_PROTOCOL"] = "http/1.1"
CGIHandler().run(app)
Note the shebang on my files is the path to my virtualenv where I have flask installed. The version of python is v2.7
I also have my main flask app (myapp.py which is also executable and with 755 permissions) file with the routes and the contents are as follows;
#!/home/username/public_html/cgi-bin/flask_app/bin/python
import os
import sys
sys.path.insert(0, '/home/aofadero/public_html/cgi-bin')#path to myapp.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def home():
return render_template("index.html")
if __name__ == "__main__":
app.run()
This file is also in my public_html/cgi-bin folder. I also have a .htaccess file which has the following content;
AddHandler cgi-script .cgi .py
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(/home/username/public_html/cgi-bin/myapp.cgi)
RewriteRule ^(.*)$ /home/username/public_html/cgi-bin/myapp.cgi/$1 [L]
Now this .htaccess file is currently in my public_html/cgi-bin folder because if I place it in public_html folder, I get a 500 error message. The only time I don't get the error is when the .htaccess file is in the cgi-bin folder. Some of the research I've done say to place it in the cgi-bin folder, others say in the public_html folder. I find that it only works for me when it's in the cgi-bin folder. If I do ./myapp.cgi I get the following error;
Status: 404 NOT FOUND
Content-Type: text/html
Content-Length: 233
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>404 Not Found</title>...
Can anyone help me please because I've tried about everything I could on my own. Right now I'm just getting ordinary html and none of the flask components are showing. Thanks
I have similar problems. I understand that an index.htm file must be placed at public_html, but when you try to do render_template("index.htm"), Flask will look for this file in the templates folder. The rendering is not actually executed. The index.htm file will always be displayed on the browser as a default page. Have you been able to find the solution ?
You don't need to include the Python script in the public_html. If you go to the Cpanel main page and search for Python. From there, you can create a Python app which will let you direct your website to run the Python script.
Application root = path to the folder your python is stored. I stored mine in a Python folder in the root of the private html.
Application url = what URL should you need to put into the browser to get that script.
Application startup file = The name of your Python script.
Application Entry point = The callable object in your Python script (in your case, it would be app).
Please see the video here for a walkthrough of this process: https://www.youtube.com/watch?v=xFxL7Mvut6g&ab_channel=Hob-iZadeAdemEfendi

Deploying flask app to Apache shared hosting

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.

Deploying Django at alwaysdata.com

I am new on django. I tried this but I can't deploy. How can I do
#!/usr/bin/python
import sys
import os
base = os.path.dirname(os.path.abspath(__file__)) + '/..'
sys.path.append(base)
os.environ['DJANGO_SETTINGS_MODULE'] = 'myfirstapp.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
AddHandler fcgid-script .fcgi
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteRule ^(media/.*)$ - [L]
RewriteRule ^(adminmedia/.*)$ - [L]
RewriteCond %{REQUEST_URI} !(cgi-bin/myproject.fcgi)
RewriteRule ^(.*)$ mysite.fcgi/$1 [L]
Here's the alwaysdata wiki entry for setting up Django with fastcgi. Only down-side: it's written in French.
Well, I don't speak French, but what it basically says is:
Create a directory named public in the folder of your django project.
In that directory create the file django.fcgi with the following content:
#!/usr/bin/python
import os, sys
_PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, _PROJECT_DIR)
sys.path.insert(0, os.path.dirname(_PROJECT_DIR))
_PROJECT_NAME = _PROJECT_DIR.split('/')[-1]
os.environ['DJANGO_SETTINGS_MODULE'] = "%s.settings" % _PROJECT_NAME
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded", daemonize="false")
Next, create a .htaccess in the public folder with the following content:
AddHandler fcgid-script .fcgi
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ django.fcgi/$1 [QSA,L]
If you're planning to include the django admin interface, create this symbolic link in your public directory:
ln -s /usr/local/alwaysdata/python/django/1.1/django/contrib/admin/media/ media
In the end your folder tree hierarchy should somehow look like this:
myproject/
__init__.py
manage.py
public/
django.fcgi
.htaccess
media/
settings.py
urls.py
myapp/
views.py
models.py
Hope this helps. I talked with the admin, and he said he will soon provide an English wiki. Let's hope this is going to happen anytime soon.
UPDATE: There is an English wiki article now.
You are trying to mix two different web server integration methods: fcgi (fast cgi) and wsgi.
Your first snippet is for a wsgi interface with the web server and is the recommended method for integrating Django with Apache. Very good resources (including examples) to help you set this up correctly can be found in the official Django docs How to use Django with Apache and mod_wsgi and the mod_wsgi docs Integration with Django
The second snippet (with AddHandler line) is for fcgi. This is the kind of interface that is more typically used to interface Django with the lighttpd and nginx web servers. Resources for setting up fcgi interface can be found in official Django docs How to use Django with FastCGI, SCGI, or AJP.
Since it looks like alwaysdata.com only uses FastCGI (fcgi) interface you are stuck with this method. It looks like there are examples on their wiki page Déployer une application Django and particulary you'll need to replace your first (wsgi) snippet with this:
#!/usr/bin/python
import os, sys
_PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, _PROJECT_DIR)
sys.path.insert(0, os.path.dirname(_PROJECT_DIR))
_PROJECT_NAME = _PROJECT_DIR.split('/')[-1]
os.environ['DJANGO_SETTINGS_MODULE'] = "%s.settings" % _PROJECT_NAME
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded", daemonize="false")
We got now (since a couple of months) an article in english:
Django on alwaysdata.com
Regards,

Categories

Resources