ClientServer PYTHON AND FLASK Basic Client Server Client
Client-Server PYTHON AND FLASK
Basic Client - Server Client • One Server • Many types of clients • All ‘connected’ using a common protocol Browser HTTP(s) Mobile App HTTP(s) Client Web Server HTTP(s) Client Desktop Application
Web Servers Industrial Strength: Development: - IIS - Node - Apache - Flask - Nginx - httpd - Litespeed … … We will use ‘Flask’
Flask Python module Can host basic commands needed for web application work • REST APIs Client App 1. API Call 5. API Return Flask Web Server 2. Web server directs API call to ‘handler’ Your APIs/ Code 4. API returns data to Web Server DB 3. API interacts with DB, gets processes data
Flask basics – server side from flask import Flask from flask_restful import Resource, Api from api. hello_world import Hello. World app = Flask(__name__) #create Flask instance api = Api(app) #api router api. add_resource(Hello. World, '/hi') #api 'endpoint'
Flask basics – server side: API from flask import Flask from flask_restful import Resource, Api from api. hello_world import Hello. World class Hello. World(Resource): def get(self): #Handles ‘get’ request return dict(example. list_examples()) def list_examples(): return exec_get_all ('SELECT id, foo FROM example_table')
Flask basics – client side import requests #HTTP library for get/ post. . . url = ’http: //locahost: 8000/hi') #api 'endpoint' response = requests. get(url, params) #HTTP GET, url=endpoint
On the ‘wire’ GET /hi HTTP/1. 1 Host: localhost: 5000 User-Agent: python-requests/2. 22. 0 Accept-Encoding: gzip, deflate Accept: */* Connection: keep-alive The request HTTP/1. 0 200 OK Content-Type: application/json Content-Length: 29 Server: Werkzeug/1. 0. 1 Python/3. 8. 0 Date: Sat, 26 Sep 2020 16: 21: 28 GMT { "1": "hello, world!" } The response
On the ‘wire’ GET /hi? a=1&b=2 HTTP/1. 1 Host: localhost: 5000 User-Agent: python-requests/2. 22. 0 Accept-Encoding: gzip, deflate Accept: */* Connection: keep-alive The request – with params HTTP/1. 0 200 OK Content-Type: application/json Content-Length: 29 Server: Werkzeug/1. 0. 1 Python/3. 8. 0 Date: Sat, 26 Sep 2020 16: 21: 28 GMT { "1": "hello, world!" } The response
- Slides: 9