Tpi Lab Python Eng
Tpi Lab Python Eng
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
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.
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
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
@app.route('/')
def hello_world():
return 'Hello World'
if __name__ == '__main__':
app.run()
3
Ioana Dogaru – Programming Technologies for Internet
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.
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.
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.
1 host
2 port
Defaults to 5000
3 debug
4 options
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.
app = Flask(__name__)
@app.route('/hello/<name>')
def hello_name(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.
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.
@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()
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
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.
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>
ETTI can be changed, and also the greeting message will be changed
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/
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;
}
<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>
{% endif %}
{% endblock %}
13
Ioana Dogaru – Programming Technologies for Internet
Once you restart the application this screen should appear in your browser:
14
Ioana Dogaru – Programming Technologies for Internet
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()
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
https://github.com/schedutron/CPAP/blob/master/Chap5/chat_serv.py
#!/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()
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
clients = {}
addresses = {}
HOST = ''
PORT = 33000
BUFSIZ = 1024
ADDR = (HOST, PORT)
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()
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:
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.
20
Ioana Dogaru – Programming Technologies for Internet
METHOD PARAMETER DESCRIPTION
fillcolor() Color name Changes the color of the turtle will use to fill a polygon
end_fill() None Close the polygon and fill with the current fill color
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
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