Вы находитесь на странице: 1из 22

Ioana Dogaru – Programming Technologies for Internet

Laboratory - Programming Technologies for Internet


INTRODUCTION TO PYTHON PROGRAMMING LANGUAGE

What is Python?
 Python is an open source, object-oriented, high-level powerful programming language.
 Developed by Guido van Rossum in the early 1990s at the National Research Institute for
Mathematics and Computer Science in Netherlands. Named after Monty Python ( British
comedy group)
 Python runs on many Unix variants, on the Mac, and on Windows.
 Available for download from http://www.python.org
Guido van Rossum  https://gvanrossum.github.io//

Features of Python

 Open source: Python is publicly available open source software; any one can use source code
that doesn't cost anything.
 Easy-to-learn: Popular (scripting/extension) language, clear and easy syntax, no type
declarations, automatic memory management, high-level data types and operations, design to read
(more English like syntax) and write (shorter code compared to C, C++, and Java) fast.
 High-level Language: High-level language (closer to human) refers to the higher level of concept
from machine language (for example assembly languages). Python is an example of a high-level
language like C, C++, Perl, and Java with low-level optimization.
 Portable: High level languages are portable, which means they are able to run across all major
hardware and software platforms with few or no change in source code. Python is portable and can
be used on Linux, Windows, Macintosh, Solaris, FreeBSD, OS/2, Amiga, AROS, AS/400 and many
more.
 Object-Oriented: Python is a full-featured object-oriented programming language, with features
such as classes, inheritance, objects, and overloading.
 Python is Interactive: Python has an interactive console where you get a Python prompt
(command line) and interact with the interpreter directly to write and test your programs. This is useful
for mathematical programming.
Interpreted: Python programs are interpreted, takes source code as input, and then compiles (to
portable byte-code) each statement and executes it immediately. No need to compiling or linking

1
Ioana Dogaru – Programming Technologies for Internet
Extendable: Python is often referred to as a "glue" language, meaning that it is capable to work in
mixed-language environment. The Python interpreter is easily extended and can add a new built-in
function or modules written in C/C++/Java code.
Libraries : Databases, web services, networking, numerical packages, graphical user interfaces, 3D
graphics, others.
Supports :Support from online Python community

Major uses of Python

 System utilities (system admin tools, command line programs).


 Web Development.
 Graphical User Interfaces (tkinter, gtk, Qt).
 Internet scripting.
 Embedded scripting.
 Database access and programming.
 Game programming.
 Rapid prototyping and development.
 Distributed programming

Python IDLE:
IDLE is an integrated development environment (an application like a word processor which helps
developers to write programs) for Python. IDLE is the Python IDE which comes with Python, built with
the tkinter GUI toolkit. It has two modes Interactive and Development.

Python-Specific Editors and IDEs:


PyCharm
Spyder
Thonny

In the following examples, Spyder IDE and Anacoda distribution for Python 3.6 version will be
used. https://www.anaconda.com/download/

Anaconda is a free and open source distribution of the Python and R programming languages for
data science and machine learning related applications that aims to simplify package management
and deployment. Package versions are managed by the package management system conda.

2
Ioana Dogaru – Programming Technologies for Internet

Learning Python by code examples

 Python and Web programming


In Python we can use several packages for internet programming – a few examples are Django,
Pyramid or Flask packages.

Example 1. Internet programming using flask package

In Spyder IDE – create a new file, introduce and run the following code: (Notice that in Anaconda
distribution the flask package is default – otherwise should be installed using pip install command.)
Save it as an example ex2.py

from flask import Flask


app = Flask(__name__)

@app.route('/')
def hello_world():
return 'Hello World'

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

Notice the message * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

3
Ioana Dogaru – Programming Technologies for Internet

* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

In browser use the following link: http://127.0.0.1:5000 .

Press Ctrl + C from Spyder interface and try again the page in the browser. The following message
will be displayed.

Importing flask module in the project is mandatory. An object of Flask class is our WSGI (Web
Server Gateway Interface) application. WSGI is the Web Server Gateway Interface. It is a
specification that describes how a web server communicates with web applications, and how web
applications can be chained together to process one request.

Flask constructor takes the name of current module (__name__) as argument.

4
Ioana Dogaru – Programming Technologies for Internet
The route() function of the Flask class is a decorator, which tells the application which URL should
call the associated function.

 The rule parameter represents URL binding with the function.

 The options is a list of parameters to be forwarded to the underlying Rule object.

In the above example, ‘/’ URL is bound with hello_world() function. Hence, when the home page of
web server is opened in browser, the output of this function will be rendered.

Finally the run() method of Flask class runs the application on the local development server.

app.run(host, port, debug, options)

All parameters are optional

Sr.No Parameters & Description

1 host

Hostname to listen on. Defaults to 127.0.0.1 (localhost). Set to ‘0.0.0.0’ to


have server available externally

2 port

Defaults to 5000

3 debug

Defaults to false. If set to true, provides a debug information

4 options

To be forwarded to underlying Werkzeug server.

Flask – Variable Rules


It is possible to build a URL dynamically, by adding variable parts to the rule parameter. This variable
part is marked as <variable-name>. It is passed as a keyword argument to the function with which
the rule is associated.

5
Ioana Dogaru – Programming Technologies for Internet

Example 2:
Introduce the following code in a Python script and run it. Run also in browser using the following link.

from flask import Flask

app = Flask(__name__)

@app.route('/hello/<name>')

def hello_name(name):

return 'Hello %s!' % name

if __name__ == '__main__':

app.run()

Notice that the rule parameter of route() decorator contains <name> variable part attached to
URL ‘/hello’. Hence, if the http://localhost:5000/hello/OziFrumoasa!!!!! is entered as a URL in the
browser, ‘OziFrumoasa!!!!!’ will be supplied to hello() function as argument.

Exercise: Modify in browser OziFrumoasa!!!! . Explain the result.

Example 3: Creating URL routes

URL Routing makes URLs in your Web app easy to remember. We will now create some URL
routes:

/hello
/members/
/members/name/

Copy the code below and save it as app.py Run the script.

from flask import Flask


app = Flask(__name__)

@app.route("/")
def index():

6
Ioana Dogaru – Programming Technologies for Internet
return "Index!"

@app.route("/hello")
def hello():
return "Hello World!"

@app.route("/members")
def members():
return "Members"

@app.route("/members/<string:name>/")
def getMember(name):
return name

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

Try in your browser the following links:

http://127.0.0.1:5000/

http://127.0.0.1:5000/hello

http://127.0.0.1:5000/members

http://127.0.0.1:5000/members/LLLL/

Exercise: Explain the results in browser. Modify the code in order to obtain different
messages in browser.

7
Ioana Dogaru – Programming Technologies for Internet

Example 4: Style Flask Pages

We will separate code and User Interface using a technique called Templates. We make the
directory called /templates/ and create the template: (test.html file) as follows:

Create the file named test.html (using for example Notepad) in a new folder named templates.

<h1>Hello {{name}}</h1>

<!DOCTYPE html>
<html>
<body>
<h1> Hello {{name}}</h1>
</body>
</html>

The Python Flask app with have a new URL route. We have changed the default port to 80,
the default HTTP port:

 Create a new file app.py outside the templates folder with the following code:

from flask import Flask, flash, redirect, render_template, request, session, abort

app = Flask(__name__)

@app.route("/")
def index():
return "Flask App!"

@app.route("/hello/<string:name>/")
def hello(name):
return render_template(
'test.html',name=name)

if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)

8
Ioana Dogaru – Programming Technologies for Internet

Run the script in Spyder IDE and in browser try the following link.

Exercise: Explain the results. Modify in the browser the size of the displayed text.

Example 5 : Styling the template

a) Change the test.html file as following. We will use the CSS style rules in html files:

<html>
<head>
<title>Website</title>
<style>
@import url(http://fonts.googleapis.com/css?family=Amatic+SC:700);

body{
text-align: center;
}
h1{
font-family: 'Amatic SC', cursive;
font-weight: normal;
color: #8ac640;
font-size: 2.5em;
}

</style>

</head>
<body>
<div class="block1">
<h1>Hello {{name}}!</h1>
<h2>Here is an interesting quote for you: </h2>
<p>
"The limits of my language are the limits of my mind. All I know is what I have words for."
</p>
<img src="http://www.naturalprogramming.com/images/smilingpython.gif">
</div>
</body>
</html>

b) Run again the app.py file in Spyder

c) run in browser (http://127.0.0.1/hello/ETTI/)


9
Ioana Dogaru – Programming Technologies for Internet

ETTI can be changed, and also the greeting message will be changed

If the image is not available:

Example 6 : Building a Flask login screen

Create this Python file and save it as app.py:

from flask import Flask


from flask import Flask, flash, redirect, render_template, request, session, abort
import os

app = Flask(__name__)

@app.route('/')
def home():
if not session.get('logged_in'):
return render_template('login.html')
else:
return "Hello Boss!"

@app.route('/login', methods=['POST'])

10
Ioana Dogaru – Programming Technologies for Internet
def do_admin_login():
if request.form['password'] == 'password' and request.form['username'] ==
'admin':
session['logged_in'] = True
else:
flash('wrong password!')
return home()

if __name__ == "__main__":
app.secret_key = os.urandom(12)
app.run(host='0.0.0.0', port=4000)

There are two routes (paths you can see in your browser URL bar) created here:

@app.route('/')
@app.route('/login', methods=['POST'])

The first one displays the login screen or the home screen, based on the condition if you are logged
in. The second route validates the login variables on login.

We create the directory /templates/. Create the file /templates/login.html with this code:

{% block body %}
{% if session['logged_in'] %}
<p>You're logged in already!</p>
{% else %}
<form action="/login" method="POST">
<input type="username" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<input type="submit" value="Log in">
</form>
{% endif %}
{% endblock %}

Run the web app using Spyder IDE and Open http://localhost:4000/

The result in browser should be:

Example 7: Adding style.css


We create the directory named /static/ with the file style.css.

11
Ioana Dogaru – Programming Technologies for Internet
* {
box-sizing: border-box;
}

*:focus {
outline: none;
}
body {
font-family: Arial;
background-color: #3498DB;
padding: 50px;
}
.login {
margin: 20px auto;
width: 300px;
}
.login-screen {
background-color: #FFF;
padding: 20px;
border-radius: 5px
}

.app-title {
text-align: center;
color: #777;
}

.login-form {
text-align: center;
}
.control-group {
margin-bottom: 10px;
}

input {
text-align: center;
background-color: #ECF0F1;
border: 2px solid transparent;
border-radius: 3px;
font-size: 16px;
font-weight: 200;
padding: 10px 0;
width: 250px;
transition: border .5s;
}

input:focus {
border: 2px solid #3498DB;
box-shadow: none;
}

.btn {
border: 2px solid transparent;
background: #3498DB;
color: #ffffff;
font-size: 16px;
line-height: 25px;
padding: 10px 0;
text-decoration: none;
text-shadow: none;

12
Ioana Dogaru – Programming Technologies for Internet
border-radius: 3px;
box-shadow: none;
transition: 0.25s;
display: block;
width: 250px;
margin: 0 auto;
}

.btn:hover {
background-color: #2980B9;
}

.login-link {
font-size: 12px;
color: #444;
display: block;
margin-top: 12px;
}

Modify the login.html template (in templates folder) as:

<link rel="stylesheet" href="/static/style.css" type="text/css">


{% block body %}
{% if session['logged_in'] %}
<p>You're logged in already!</p>
{% else %}

<form action="/login" method="POST">


<div class="login">
<div class="login-screen">
<div class="app-title">
<h1>Login</h1>
</div>

<div class="login-form">
<div class="control-group">
<input type="text" class="login-field" value="" placeholder="username"
name="username">
<label class="login-field-icon fui-user" for="login-name"></label>
</div>

<div class="control-group">
<input type="password" class="login-field" value="" placeholder="password"
name="password">
<label class="login-field-icon fui-lock" for="login-pass"></label>
</div>

<input type="submit" value="Log in" class="btn btn-primary btn-large btn-block" >


<br>
</div>
</div>
</div>
</form>

{% endif %}
{% endblock %}

13
Ioana Dogaru – Programming Technologies for Internet

Once you restart the application this screen should appear in your browser:

If we introduce for testing admin and password

we obtain the following page:

14
Ioana Dogaru – Programming Technologies for Internet

What about logout?

As you may have seen, there is no logout button or functionality. Creating that is very easy.
The solution proposed below is only one of the many solutions. We create a new route /logout
which directs to the function logout(). This function clears the session variable and returns to
the login screen.

@app.route("/logout")
def logout():
session['logged_in'] = False
return home()

The full code of app.py file will be:

from flask import Flask


from flask import Flask, flash, redirect, render_template, request, session, abort
import os

app = Flask(__name__)

@app.route('/')
def home():
if not session.get('logged_in'):
return render_template('login.html')
else:
return "Hello Boss! <a href='/logout'>Logout</a>"

@app.route('/login', methods=['POST'])
def do_admin_login():
if request.form['password'] == 'password' and request.form['username'] ==
'admin':
session['logged_in'] = True
else:
flash('wrong password!')
return home()

@app.route("/logout")
def logout():
session['logged_in'] = False
return home()

if __name__ == "__main__":
app.secret_key = os.urandom(12)
app.run(host='0.0.0.0', port=4000)

Run again in Spyder the app. py file (as seen in the picture)

15
Ioana Dogaru – Programming Technologies for Internet

Run in browser the following link:

Example 8 : Chat application: - (Server/client application)

https://github.com/schedutron/CPAP/blob/master/Chap5/chat_serv.py

The following scripts will be used : chat_serv.py and chat_clnt.py


16
Ioana Dogaru – Programming Technologies for Internet

Chat_serv.py file is as following: (The file is also provided in the lab)

#!/usr/bin/env python3
"""Server for multithreaded (asynchronous) chat application."""
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread

def accept_incoming_connections():
"""Sets up handling for incoming clients."""
while True:
client, client_address = SERVER.accept()
print("%s:%s has connected." % client_address)
client.send(bytes("Greetings from the cave! Now type your name and press enter!", "utf8"))
addresses[client] = client_address
Thread(target=handle_client, args=(client,)).start()

def handle_client(client): # Takes client socket as argument.


"""Handles a single client connection."""

name = client.recv(BUFSIZ).decode("utf8")
welcome = 'Welcome %s! If you ever want to quit, type {quit} to exit.' % name
client.send(bytes(welcome, "utf8"))
msg = "%s has joined the chat!" % name
broadcast(bytes(msg, "utf8"))
clients[client] = name

while True:
msg = client.recv(BUFSIZ)
if msg != bytes("{quit}", "utf8"):
broadcast(msg, name+": ")
else:
client.send(bytes("{quit}", "utf8"))
client.close()
del clients[client]
broadcast(bytes("%s has left the chat." % name, "utf8"))
break

def broadcast(msg, prefix=""): # prefix is for name identification.


"""Broadcasts a message to all the clients."""

for sock in clients:


sock.send(bytes(prefix, "utf8")+msg)

clients = {}
addresses = {}

HOST = ''
PORT = 33000
BUFSIZ = 1024
ADDR = (HOST, PORT)

SERVER = socket(AF_INET, SOCK_STREAM)


SERVER.bind(ADDR)

17
Ioana Dogaru – Programming Technologies for Internet
if __name__ == "__main__":
SERVER.listen(5)
print("Waiting for connection...")
ACCEPT_THREAD = Thread(target=accept_incoming_connections)
ACCEPT_THREAD.start()
ACCEPT_THREAD.join()
SERVER.close()

From Anaconda command prompt we run the script: python chat_serv.py

Change the folder for the corresponding scripts as in your computer!!

We open another command prompt in order to run the client script:


We introduce the host as 127.0.0.1 (port can be skipped). A user interface will be opened.

18
Ioana Dogaru – Programming Technologies for Internet

We can add another client to the chat. We open another command prompt in order to run the
client script:

The application can be tested on multiple computers from the network.

Exercise

Try chat server/client application on multiple computers. (Find the ip configuration with
ipconfig command from the command prompt)

19
Ioana Dogaru – Programming Technologies for Internet

Example 9: Run Spyder and execute the following scripts example for Snake game

Run snake.py script. The game has a user interface (notice the tkinter package for graphical user
interface development).  from tkinter import* import the package.
Notice also the class keyword that introduce a class and def keyword that introduce a function in
Python. Follow the code and remark the syntax.

Exercise, change the color of the background, of the snake, food and also change the speed of the
game

Example 10: “Turtle” is a Python feature like a drawing board, which lets us command a turtle to
draw all over it! We can use functions like turtle.forward(…) and turtle.right(…) which can move the
turtle around.

Commonly used turtle methods are:

METHOD PARAMETER DESCRIPTION

Turtle() None Creates and returns a new tutrle object

forward() amount Moves the turtle forward by the specified amount

backward() amount Moves the turtle backward by the specified amount

right() angle Turns the turtle clockwise

left() angle Turns the turtle counter clockwise

penup() None Picks up the turtle’s Pen

20
Ioana Dogaru – Programming Technologies for Internet
METHOD PARAMETER DESCRIPTION

pendown() None Puts down the turtle’s Pen

up() None Picks up the turtle’s Pen

down() None Puts down the turtle’s Pen

color() Color name Changes the color of the turtle’s pen

fillcolor() Color name Changes the color of the turtle will use to fill a polygon

heading() None Returns the current heading

position() None Returns the current position

goto() x, y Move the turtle to position x,y

begin_fill() None Remember the starting point for a filled polygon

end_fill() None Close the polygon and fill with the current fill color

dot() None Leave the dot at the current position

stamp() None Leaves an impression of a turtle shape at the current location

shape() shapename Should be ‘arrow’, ‘classic’, ‘turtle’ or ‘circle’

Copy the following code into Spyder IDE (save the file for example as ex1.py)

import turtle
colors = ['red', 'purple', 'blue', 'green', 'orange', 'yellow']
t = turtle.Pen()
turtle.bgcolor('black')
for x in range(360):
t.pencolor(colors[x%6])
t.width(x/100 + 1)
t.forward(x)
t.left(59)

turtle.exitonclick()

21
Ioana Dogaru – Programming Technologies for Internet

Run the code:

References:

https://www.w3resource.com/python/python-tutorial.php
https://realpython.com/python-ides-code-editors-guide/
https://docs.python.org/3/tutorial/index.html
https://www.tutorialspoint.com/flask/flask_application.htm
chat-server application - https://medium.com/swlh/lets-write-a-chat-app-in-python-f6783a9ac170
A.M. Kuchling https://media.readthedocs.org/pdf/fiftyexamples/latest/fiftyexamples.pdf
https://github.com/ergo14/Snake-Game-with-Python-Tkinter
https://pythonspot.com/flask-web-app-with-python/
http://www.tornadoweb.org/en/stable/
https://www.anaconda.com/download/

22

Вам также может понравиться