Search

14 January, 2018

How to run a Python program on the internet from anywhere?


I want to run a python program whenever I need and get some information out of it. The problem is, I want to call that through internet. And I want to show the content on a web page or some UI container. That's it. Let put this as a requirement.

Problem: Display some information on my web page calculated by a python program

How do we do it on our local computer? We run our program as : python my_program.py.
So maybe I can do something like: www.mywebsite.com/my_program.py . Can we? No idea.

I expect to collect the response in some variable (no idea how I can create a variable in the first place on html) and then display the contents of this variable. Displaying a simple text on html is known, so that should be easy.

The Program

You must remember that we want some information from our program . It's a basic GET call where you just ask for some information from a server. You may or may not pass some inputs while doing this.



from flask import Flask
from flask_restful import Api, Resource

app = Flask(__name__)
api = Api(app)

class Hello(Resource):
    def get(self, person_name):
        return 'Hello %s' % person_name


api.add_resource(Hello, '/hello/<string:person_name>')

if __name__ == '__main__':
    app.run()


So what's going on here? This is not the simple hello_world program as promised. Well it almost is.

  • We create an app from class Flask and an api object from Api class for the app created.
  • Since we are want to write a GET api, we define a "getfunction inside our  Hello class that inherits from Resource.
  • And at last, we register our function with a url. 
Note: The url accepts a string , with argument variable as "person_name" and passes that to our function . So the variable 'person_name' should be same as accepted by the 'get' function.

Save the above code in a file and run this. This is what you will see.


================ RESTART: F:\Projects\Flask-Api\api_script.py ================
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [24/Sep/2017 15:11:43] "GET /hello/arindam HTTP/1.1" 200 -
Now visit the link for e.g : http://127.0.0.1:5000/hello/YourName

 "Hello YourName".

Deployment

Now we need to place our running SERVER someplace which is accessible 24/7. We obviously cannot use our server running on local PC. I am going to use pythonanywhere for this . As they advertise,

" Host, run, and code Python in the cloud! "

So we are going to use it as a host. We are going to open a console, and check if we have everything that we need. Generally , the environment already has all our favorite modules and tools installed. 


This is the Console tab. Click on "Bash" to launch a new bash console. Then launch python . Try to import the modules that we have used above.



If you can see this, you are ready to go. Else:

pip install flask
pip install flask_restful


 Now go back by clicking on "Dashboard". Click on the tab "Files". It's probably empty right now. Create a new directory by providing a name and clicking on 'New Directory'. Use the " Upload a file " to add the above file created. (Or you can checkout from git


I created the folder "mysite" and upload the file "flask_app" which has the same code . Now go to Dashboard and click on "Web". Click on "Add a new web app" .


  • Select Web domain name (example "xyz"
  • "Flask" as python web framework 
  •  Python 2.7 
  •  Put the path as /home/xyz/mysite/flask_app.py
After above wizard is finished, you will see the config param of your website. Change it like shown in the pic below.



The section under "Code: " should be like above. Now click on the WSGI python file and edit it like shown below:


Save it . Now go back the "Web" tab from the Dashboard and run you website. "Run until 3 months" button. 

  • Now launch browser. 
  • Visit the page , "www.xyz.pythonanywhere.com/hello/YourText"
This is the same code on my website.
 TADA

Now you can use any module to call this API from your scripts and you will get this response . Now you are ready to create more complicated response.

Problem 2: We want to know, what people used in the above hello url while trying it out.. So design a way to store this info and display the same .

Lets prepare a list to steps to do that. 
  • Setup Database in pythonanywhere.com (Setup usr, pwd for the DB).
  • Install 'flask_sqlalchemy' using pip.
  • Create  database and tables inside it.
  • In our api_script.py file, add config for connecting to database. Refer this.

After you setup your database, you will be seeing some details under your 'Database' tab. 

The api_script.py file should be modified like shown below.



from flask import Flask
from flask_restful import Api, Resource
from graph_rss_feed import MyRssParser, GenerarateGraphs
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['DEBUG'] = True
api = Api(app)

SQLALCHEMY_DATABASE_URI = "mysql+mysqlconnector://{username}:{password}@{hostname}/{databasename}".format(
    username="yourusername",
    password="yourpassword",
    hostname="username.mysql.pythonanywhere-services.com",
    databasename="username$Hello_keywords",
)
app.config["SQLALCHEMY_DATABASE_URI"] = SQLALCHEMY_DATABASE_URI
app.config["SQLALCHEMY_POOL_RECYCLE"] = 299
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)


class Hello(Resource):
    def get(self, person_name):
        w = Words(content=person_name)
        db.session.add(w)
        db.session.commit()
        return 'Hello %s' % person_name

class AllWords(Resource):
    def get(self):
        all_words = Words.query.all()
        list_words_str = ','.join([word_obj.content for word_obj in all_words])
        return 'Here are all words: %s' % list_words_str


class Words(db.Model):
    __tablename__ = "words"

    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.String(512))

api.add_resource(Hello, '/hello/<string:person_name>')
api.add_resource(AllWords, '/words/')

if __name__ == '__main__':
    app.run() 

Now that our code is ready , let's do some finishing touches. pythonanywhere works with the help of a WSGI file. Refer the picture below to find the WSGI file.

WSGI link on WEB Tag in Pythonanywhere.com

Click on the file to edit it. Edit it as following.

# This file contains the WSGI configuration required to serve up your
# web application at http://<your-username>.pythonanywhere.com/
# It works by setting the variable 'application' to a WSGI handler of some
# description.
#
# The below has been auto-generated for your Flask project

import sys

# add your project directory to the sys.path
project_home = u'/home/arindam31/MyRssFeedProject/SkillDemand'
if project_home not in sys.path:
    sys.path = [project_home] + sys.path

# import flask app but need to call it "application" for WSGI to work
from api_script import app as application

We are done. Reload the web site from the WEB tab and visit the url:

 www.myweb.pythonanywhere.com/hello/MyWorld

 www.myweb.pythonanywhere.com/words

See the results. I know this was long . But it's totally awesome when everything works . Best of luck.

No comments:

Post a Comment