Skip to content
Snippets Groups Projects
Commit a9a759fd authored by ChevrierVincent's avatar ChevrierVincent
Browse files

maj code web service

parent b2999a53
No related branches found
No related tags found
No related merge requests found
from flask import Flask, jsonify, request, url_for
app = Flask(__name__)
# define some data
data = [
{
'id': 1,
'name': 'motor async',
'description': 'Ma bioutifoul motor with plein de puissance',
'done': False
},
{
'id': 2,
'title': 'PV pannel',
'description': 'provide you nice power',
'power': 1000
}
]
@app.route('/data', methods=['GET'])
def get_tasks():
return jsonify({'data': data})
@app.route('/dataSole', methods=['GET'])
def requete():
args = request.args
print ("print info",args) # For debugging
return "yes"
@app.route('/query-example')
def query_example():
# if key doesn't exist, returns None
language = request.args.get('language')
a =request.args.get('a')
return '''<h1>The language value is: {} et a est {}</h1>'''.format(language,a)
@app.route('/qa-example2',methods=['GET','POST'])
def qa_example():
if request.method == 'POST':
return "c'est un post"
else:
language = request.args.get('language')
a = request.args.get('a')
return '''<h1>The language value is: {} et a est {}</h1>'''.format(language, a)
@app.route('/')
def index():
return "this is the base page for my bioutifoul app !\p" + \
"<p>test page racine. connexion sur http://127.0.0.1:5000/ <a href=\"http://127.0.0.1:5000\">Lelien attention ça boucle</a>" + \
"\n url pour requete"+str(url_for('requete'))
app.run(debug=True)
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test des serveur</title>
</head>
<body>
<p>test page racine. connexion sur http://127.0.0.1:5000/ <a href="http://127.0.0.1:5000/">Lelien</a> ?<br/>
</p>
<p> connexion sur date http://127.0.0.1:5000/ <a href="http://127.0.0.1:5000/data">Lelien2</a> ?<br/>
</p>
<p> test args http://127.0.0.1:5000/ <a href="http://127.0.0.1:5000/dataSole?a=4&c=34">Lelien3</a> ?<br/>
</p>
<p> test args http://127.0.0.1:5000/ <a href="http://127.0.0.1:5000/query-example?a=4&c=34&language=python">Lelien4</a> ?<br/>
</p>
<p> test args + get http://127.0.0.1:5000/ <a href="http://127.0.0.1:5000/query-example2?a=4&c=34&language=pythonjava">Lelien5</a> ?<br/>
</p>
</body>
</html>
\ No newline at end of file
File moved
""" how to ask in python a web service """
# see https://openweathermap.org/api
# what is possible : https://openweathermap.org/price#weather
......@@ -37,8 +37,9 @@ print(answer.text)
# exo 1
requestSol=requestTxt+"&lang=fr"
# solution to exo 1
requestSol=requestTxt+"&lang=fr"+"&mode=xml"
print (requestSol)
answer=requests.get(requestSol)
print("sol",answer.text)
File moved
File moved
File moved
# Documentation for the examples
*V Chevrier Dec 21*
*V Chevrier Nov 22*
## What to know
In python, use of **requests** package that enables call to web service (as html addresses do)
and use of **flask** package for web services.
In python, use of **requests** package that enables call to web service (as html addresses do) -->client side
and use of **flask** package for web services ---> server side
## Examples Client side
### File appli1.py
## Examples
### File client1.py
Simple call to a distant web service : ask for weather in Nancy
see https://openweathermap.org/current#geo for more information
#### Questions
* Questions
- Explain why we need to write ***print(answer.text)***
- what means the string output format ?
#### Exercise:
* Explain why we need to write ***print(answer.text)***
* what means the string output format ?
* Exercises:
1. Change response format to XML, the language as French
2. learn how to ask for weather forecast (with free version)
......@@ -24,56 +26,70 @@ see https://openweathermap.org/current#geo for more information
https://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=a2cabf37326f4cf77d2948c17c62705a
4. Explain how to pass parameters to a web service
#### API reference
**API reference**
[https://openweathermap.org/api](https://openweathermap.org/price#weather)
have a look on it to learn what is **possible** and how
1. all requests need an id
2. there is a limit on the number of requests each day
## Examples: learn how to define services (and how to call them)
## Examples server and client : learn how to define services (and how to call them from python client)
### A) serviceT1 (clientT1)
***Lessons learned*** how to define a server and two services
definition of 2 services on the server
- one at root basic service (just returns a string)
- one called *bonjour* that takes a ***nom*** as param and say bonjour to nom if exists
### B) serviceT2 / serviceT2json (and cleinetT2/clientT2json)
***Lessons learned*** use of *external* code in services and the use of JSON format
T2 Simple service to show that returned value can change over time
The returned values are as **text** format.
T2j
Simple service to show that returned value can change over time.
The returned values are as **json** format.
In client
- How is managed the json format?
- Can you see an advantage to use it?
### A) exemple1 (and askex1)
basic service (just returns a string) and code for requests
### B) serviceT3 (and clientT3)
### B) argument.py / askarg.py
A server to illustrate the use of arguments.
***Lessons learned*** use of arguments in services
Services :
- service0
- service0
Shows how to build a simple service that
- gets the parameters and their values
- returns them as a list of couple ou value
The returned values are as text format.
- exemple3
How to get the value of a parameter
Note that the parameter are in Json format
- exemple3
How to get the value of a parameter ***valeur**
Note that the parameter are in Json format but ....
What is the type of the values we get ??
- exemple 4 et exemple5 shows how to get typed values
### C) service1.py/askservice1.py
Simple service to show that returned value can change over time
The returned values are as **text** format.
- exemple 4 et exemple5 shows how to get typed values if params are in JSON
Exercices: code the client for the services not treated in example file.
### C') service1j.py/askservice1j.py
Simple service to show that returned value can change over time.
The returned values are as **json** format.
In askservice1 client
- How is managed the json format?
- Can you see an advantage to use it?
### service3.py
### serviceT4.py
Use of global variables
Exercice: code the client
## More interesting
### The shutdown problem
When the server is running it uses a givent port on the machine and forbids another server to be run.
##More interesting
### The shutdown problem (ServerShutDown.py)
When the server is running it uses a givent port on the machine and forbids another server to be run. If python ends improperly, the port can be "blocked".
According to your programmig environment, it can be very difficult to shutdown/kill the server.
......@@ -83,6 +99,7 @@ The file ***servershutdown.py*** shows how to integrate a shutdown service in th
serverNonLocal.py illustates how to have a non local server
Shows how to build a server with several services
### Misc
See how the root return results as html
app1 directory :
# See how toreturn results as html/use html to ask for services (just core ideas )
......@@ -17,7 +17,7 @@ def shutdown():
return 'Server shutting down...'
@app.route('/service0') # l'adresse sera service0 sur le serveur, le code en dessous sera la fonction appelée
@app.route('/service0') # un service peu importe lequele
def requete():
args = request.args
print ("print info",args.values(),args.keys(),args.items()) # For debugging
......
from flask import Flask, request # on importe le necessaire
app = Flask(__name__) # notre appli
@app.route('/service0') # l'adresse sera service0 sur le serveur, le code en dessous sera la fonction appelée
def requete():
args = request.args
print ("print info",args.values(),args.keys(),args.items()) # For debugging
rep=""
for k,v in args.items():
print (k,v)
rep+="("+k+","+v+")"
return rep
# http://127.0.0.1:5000/service0?a=4&c=34 # exemple de texte à saisir dans un navigateur
app.run(debug=True)
\ No newline at end of file
......@@ -16,8 +16,9 @@ def dire_bonjour():
nom='inconnu'
return 'bonjour '+nom
#exemple de requete
#http://127.0.0.1:5000/
#http://127.0.0.1:5000/bonjour
#http://127.0.0.1:5000/bonjour?nom=vincent
app.run(debug=True)
\ No newline at end of file
app.run(debug=True)
File moved
File moved
File moved
File moved
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment