One query we often hear from people starting out with PythonAnywhere is “how do I turn this
script I’ve written right into a internet site so that other people can run it?”
That’s in reality a bigger subject matter than you might imagine, and a whole solution would wind up
having to give an explanation for almost the whole lot approximately web improvement.So we won’t do all of that in this
weblog publish :-)The top news is that simple scripts can often be changed into simple web sites
pretty effortlessly, and in this blog publish we’ll work thru multiple examples.
Let’s get started out!
The simplest case: a script that takes a few inputs and returns an output¶
Let’s say you have got this Python three.x script:
number1 = waft(input(“Enter the first range: “))
number2 = go with the flow(enter(“Enter the second variety: “))
answer = number1 + number2
print(“The sum of your numbers is “.format(answer))
Obviously that’s a great-easy example, however numerous more complicated scripts
observe the same sort of form.For instance, a script for a economic analyst may
have these equivalent steps:
Get statistics approximately a particular inventory from the user.
Run a few kind of complex analysis on the information.
Print out a result pronouncing how right the set of rules thinks the stock is as an funding.
The point is, we have 3 phases, input, processing and output.
(Some scripts have extra levels
– they accumulate some data, do some processing, accumulate a few extra facts, do greater processing, and so on, and
subsequently print out a result.We’ll come directly to those afterward.)
Let’s paintings via how we’d
change our 3-segment input-manner-output script right into a website.
In a website’s code, we don’t have get right of entry to to the Python input or print functions,
so the enter and output phases could be exclusive – however
the processing phase may be similar to it was within the unique script.
So the first step is to extract our processing code into a feature so that it is able to be
re-used.For our instance, that leaves us with something like this:
def do_calculation(number1, number2):return number1 + number2number1 = glide(input(“Enter the first range: “))
number2 = float(input(“Enter the second one variety: “))
answer = do_calculation(number1, number2)
print(“The sum of your numbers is “.layout(solution))
Simple sufficient.In actual-global instances like the stock-evaluation then of path there could
be more inputs, and the do_calculation function could be considerably more complicated, but
the theory is the same.
Step 2: create a website¶
Firstly, create a PythonAnywhere account if you haven’t already.A free “Beginner” account is enough for this educational.
Once you’ve signed up, you’ll be taken to the dashboard, with a excursion window.It’s really worth going via
the tour so that you can learn the way the web page works – it’ll handiest take a minute or so.
At the end of the excursion you’ll be supplied with some options to “analyze more”.You can simply click on “End excursion” here,
due to the fact this academic will tell you all you want to recognise.
Now you’re offered with the PythonAnywhere dashboard.I advise you take a look at your email and verify your electronic mail deal with –
otherwise if you overlook your password later, you received’t be able to reset it.
Now you want to create a website, which requires a web framework.
The easiest net framework to get began with when creating this type of component is
Flask; it’s quite simple and doesn’t have a variety of the integrated
stuff that other net frameworks have, however for our functions that’s an excellent thing.
To create your website, visit the “Web” web page the usage of the tab near the top right:
Click at the “Add a brand new net app” button to the left.This will pop up a “Wizard” which allows you to configure your web site.If you’ve got a loose account, it’ll seem like this:
If you made a decision to move for a paid account (thank you :-), then it will likely be a bit distinct:
What we’re doing in this web page is specifying the host call inside the URL that human beings will input to peer your website.Free bills will have one internet site, and it must be at yourusername.pythonanywhere.com.Paid accounts have the option of the usage of their personal custom host names in their URLs.
For now, we’ll stick with the free choice.If you have a loose account, just click the “Next” button, and when you have a paid one, click on the checkbox next to the yourusername.pythonanywhere.com, then click on “Next”.This will take you on to the following page inside the wizard.
This web page is in which we pick out the net framework we need to use.We’re the usage of Flask, so click on that one to move directly to the next web page.
PythonAnywhere has various versions of Python mounted, and every model has its associated model of Flask.You can use one-of-a-kind Flask versions to those we deliver with the aid of default, however it’s a little more difficult (you want to apply a thing referred to as a virtualenv), so for this educational we’ll create a domain the use of Python three.6, with the default Flask version.Click the option, and also you’ll be taken to the subsequent page:
This web page is calling you in which you need to position your code.Code on PythonAnywhere is stored in your private home directory, /home/yourusername, and in its subdirectories.Flask is a particularly lightweight framework, and you can write a easy Flask app in a unmarried record.PythonAnywhere is looking you in which it have to create a listing and put a unmarried file with a truly surely simple website.The default must be high-quality; it’s going to create a subdirectory of your own home directory known as mysite after which will put the Flask code into a document referred to as flask_app.py interior that directory.
(It will overwrite some other record with the equal call, so if you’re not the usage of a brand new PythonAnywhere account, make sure that the report that it’s were given in the “Path” input box isn’t certainly one of your current documents.)
Once you’re sure you’re OK with the filename, click on “Next”.There might be a short pause while PythonAnywhere sets up the internet site, and then you’ll be taken to the configuration web page for the site:
You can see that the host call for the web page is at the left-hand side, together with the “Add a brand new web app” button.If you had a couple of web sites on your PythonAnywhere account, they could seem there too. But the only that’s currently decided on is the only you just created, and in case you scroll down a bit you can see all of its settings.We’ll ignore maximum of those for the instant, but one this is worth noting is the “Best before date” phase.
If you have got a paid account, you received’t see that – it only applies to loose money owed.But if you have a loose account, you’ll see something announcing that your web site may be disabled on a date in three months’ time.Don’t worry!You can keep a free web page up and walking on PythonAnywhere for so long as you need, without having to pay us a penny.But we do ask you to log in sometimes and click the “Run till three months from today” button, just so that we recognise you’re nevertheless interested in keeping it jogging.
Before we do any coding, let’s test out the website online that PythonAnywhere has generated for us by using default.Right-click the host name, simply after the phrases “Configuration for”, and select the “Open in new tab” alternative; this may (of course) open your web site in a brand new tab, that’s useful whilst you’re developing – you may preserve the website open in one tab and the code and different stuff in another, so it’s simpler to check out the effects of the changes you’re making.
Here’s what it have to appear like.
OK, it’s pretty easy, however it’s a start.Let’s take a look at the code!Go again to the tab displaying the internet site configuration (retaining the only showing your site open), and click on at the “Go to directory” hyperlink next to the “Source code” bit inside the “Code” segment:
You’ll be taken to a extraordinary web page, displaying the contents of the subdirectory of your home listing in which your internet site’s code lives:
Click at the flask_app.py report, and you’ll see the (actually definitely easy) code that defines your Flask app.It looks as if this:
It’s worth working through this line-by using-line:
As you’d count on, this hundreds the Flask framework so you can use it.
This creates a Flask application to run your code.
This decorator specifies that the following feature defines what occurs whilst a person goes to the region “/” on your website – eg. if they visit http://yourusername.pythonanywhere.com/.If you desired to outline what happens after they visit http://yourusername.pythonanywhere.com/foo then you’d use @app.route(‘/foo’) alternatively.
def hello_world():return ‘Hello from Flask!’
This easy characteristic just says that when someone is going to the location, they get again the (unformatted) text “Hello from Flask”.
Try converting it – as an example, to “This is my new vivid Flask app”.Once you’ve made the alternate, click on the “Save” button at the pinnacle to keep the report to PythonAnywhere:
…then the reload button (to the far proper, searching likecurved arrows creating a circle), which stops your website and then starts offevolved it again with the sparkling code.
A “spinner” will appear subsequent to the button to tell you that PythonAnywhere is running.Once it has disappeared, go to the tab showing the internet site again, hit the web page refresh button, and you’ll see that it has changed as you’d anticipate.
Step three: make the processing code to be had to the web app¶
Now, we need our Flask app with a purpose to run our code.We’ve already extracted it right into a
characteristic of its very own.It’s typically a great idea to preserve the web app code – the primary stuff to
display pages – break free the greater complex processing code (in spite of everything, if we have been doing the stock analysis
instance rather than this simple add–numbers script, the processing may be heaps of traces lengthy).
So, we’ll create a brand new file for our processing code.Go lower back to the browser tab that’s showing your editor page; up on the top, you’ll see
“breadcrumb” hyperlinks displaying you wherein the record is saved.They’ll be a chain of listing names separated
by means of “/” characters, each one apart from the remaining being a link.
The closing one, just before the name of the report containing your Flask code,
will probably be mysite.Right-click on on that, and open it in a brand new browser tab – the brand new tab
will display the directory list you had earlier than:
In the enter near the pinnacle proper, where it says “Enter new record name, eg. hiya.py”, enter the call
of the record in order to comprise the processing code.Let’s (uninventively) name it processing.py.
Click the “New document” button, and you’ll have another editor window open, displaying an empty file.
Copy/paste your processing function into there; that means that the record ought to definitely include this
def do_calculation(number1, number2):go back number1 + number2
Save that record, then move lower back to the tab you stored open that incorporates the Flask code.At the
top, upload a brand new line just after the line that imports Flask, to import your processing code:
from processing import do_calculation
While we’re at it, permit’s additionally upload a line to make debugging less difficult if you have a typo
or other blunders within the code; just after the road that says
app.config[“DEBUG”] = True
Save the report; you’ll see which you get a warning icon subsequent to the brand new import line.If you pass your
mouse pointer over the icon, you’ll see the details:
It says that the function turned into imported however is not being used, that’s completely proper!That
moves us directly to the following step.
Step four: Accepting enter¶
What we want our website to do is show a web page that permits the person to go into two numbers.To do
that, we’ll change the prevailing function this is run to show the page.Right now we have this:
def hello_world():go back ‘This is my new vivid Flask app’
We want to show greater than textual content, we want to display some HTML.Now, the high-quality way to do HTML in
Flask apps is to use templates (which assist you to preserve the Python code that Flask desires in separate files from
the HTML), however we’ve other tutorials that move into the info of that.In this case
we’ll simply positioned the HTML proper there inside our Flask code – and at the same time as we’re at it, we’ll rename the
def adder_page():return ”’
Enter your numbers:
We gained’t pass into the info of how HTML works here, there are plenty of amazing tutorials on-line
and one that suits the manner you study is only a Google search away.For now, all we want to recognize is that
wherein we have been previously returning a unmarried-line string, we’re now returning a multi-line one
(that’s what the 3 charges in a line suggest, in case you’re not familiar with them – one string cut up
over more than one traces).The multi-line string incorporates HTML code, which just presentations a page
the person to enter two numbers, and a button that says “Do calculation”.Click at the editor’s
“reload website” button:
…and then test out your internet site again in the tab that you (with a bit of luck) stored open, and also you’ll
see some thing like this:
However, as we haven’t done something to cord up the input to the processing, clicking the “Do calculation”
button gained’t do whatever but reload the page.
Step 5: validating enter¶
We could at this degree move directly to including on the code to do the calculations, and I was
in the beginning planning to do that right here.But after considering it, I realised that doing that
could essentially be teaching you to shoot yourself within the foot…When you put a website up
at the Internet, you have to permit for the truth that the human beings using it’s going to make mistakes.
If you created a website that allowed humans to enter numbers and add them, subsequently someone
will kind in “wombat” for one of the numbers, or some thing like that, and it would be embarrassing
if your website online replied with an inner server blunders.
So let’s upload on some fundamental validation – that is, some code that makes positive that human beings aren’t
providing us with random marsupials instead of numbers.
A precise internet site will, while you input an invalid enter, show the page again with an error message
in it.A terrible internet site will display a web page saying “Invalid enter, please click on the lower back button
and strive again”.Let’s write an excellent internet site.
The first step is to exchange our HTML in order that the person viewing the page can click on the “Do calculation”
button and get a reaction.Just change the road that asserts
So that it says this:
What meaning is that previously we had a form, but now we have a shape that has an “movement”
telling it that after the button that has the kind “publish” is clicked, it need to request the equal
web page as it’s far already on, but this time it ought to use the “submit” approach.
(HTTP methods are greater bits of statistics that are tacked directly to requests which can be made
by a browser to a server.The “get” technique, as you might expect, method “I simply need to get a
web page”.The “post” method approach “I need to provide the server with a few statistics to save or
system”.There are widespread reams of information that I’m skipping over here, however that’s the most
vital stuff for now.)
So now we have a manner for facts to be despatched lower back to the server.Reload the web site using the button
inside the editor, and refresh the page inside the tab in which you’re viewing your web page.Try entering a few
numbers, and click on the “Do calculation” button, and also you’ll get… an incomprehensible mistakes message:
Well, possibly now not absolutely incomprehensible.It says “technique not allowed”.Previously we were
the usage of the “get” approach to get our page, but we simply told the shape that it must use the “publish” technique
when the facts changed into submitted.So Flask is telling us that it’s no longer going to allow that web page to
be asked with the “put up” method.
By default, Flask view features handiest accept requests the use of the “get” method.It’s smooth to trade that.
Back inside the code report, where we’ve got this line:
…replace it with this:
@app.direction(“/”, methods=[“GET”, “POST”])
Save the file, hit the reload button inside the editor, then visit the tab displaying your web page; click on returned
to break out from the error web page if it’s still showing, then enter a few numbers and click the
“Do calculation” button once more.
You’ll be taken returned to the page without a errors.Success!Kind of.
Now allow’s upload the validation code.The numbers that had been entered could be made to be had to us
in our Flask code through the shape characteristic of a global variable known as request.So we are able to upload
validation logic with the aid of the use of that.The first step is to make the request variable to be had by
uploading it; trade the line that says
from flask import Flask, request
Now, add this code to the view feature, before the go back assertion:
mistakes = “”if request.approach == “POST”:number1 = Nonenumber2 = Nonetry:number1 = float(request.shape[“number1”])besides:errors += “
!r is not a range of.
\n”.format(request.shape[“number1”])try:number2 = waft(request.form[“number2”])except:mistakes += “
!r is not more than a few.
Basically, we’re announcing that if the technique is “submit”, we do the validation.
Finally, add a few code to place the ones mistakes into the web page’s HTML; replace the bit that
returns the multi-line string with this:
Enter your numbers: