CSCI 2133
CSCI 2133 – Rapid Programming Techniques for Innovation
A Python based framework Django Crash Lesson
CSCI 2133 Rapid Programming Techniques for Innovation A Python - - PowerPoint PPT Presentation
CSCI 2133 Rapid Programming Techniques for Innovation A Python based framework Django Crash Lesson CSCI 2133 2 Previous Lecture Python Data Manipulation CSCI 2133 Agenda Django Overview Learn Django by examples
CSCI 2133
A Python based framework Django Crash Lesson
CSCI 2133
2
CSCI 2133
3
CSCI 2133
4
interface
emplating system
framework
CSCI 2133
5
django-admin startproject myshop
CSCI 2133
6
CSCI 2133
7
CSCI 2133
python m manage.py star artap app home me
8
CSCI 2133
m k d i r t e m p l a t e s
W e b u i l t a v e r y s i m p l e h t m l p a g e c a l l e d “ h o m e . h t m l ”
u r l s . p y
9
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls', namespace='home')), ]
CSCI 2133
10
from django.http import HttpResponse from django.template.loader import render_to_string def base(request): rendered = render_to_string('base.html') return HttpResponse(rendered)
Views.py is the web UI interface to help Django find template.
from django.conf.urls import url from . import views app_name = 'home' urlpatterns = [ url(r'^$', views.base, name='base'), ]
Urls.py is the configuarion file to route the http request to corresponding temaple (here we refer to the base function in views.py). And base function points at the template we specified.
CSCI 2133
11
CSCI 2133
12
CSCI 2133
13
CSCI 2133
14
cURL (pronounced 'curl') is a computer software project providing a library and command-line tool for transferring data using various protocols. The cURL project produces two products, libcurl and cURL. It was first released in 1997. The name stands for "Client URL".The original author and lead developer is the Swedish developer Daniel Stenberg.
CSCI 2133
curl -v https://web.cs.dal.ca/~gang/csci2133-project/step-db/login- all.php
curl -o out.json https://web.cs.dal.ca/~gang/csci2133-project/step- db/login-all.php
Get Same as output
curl -o https://web.cs.dal.ca/~gang/csci2133-project/step-db/login-rest- service.php? username=test1&password=12345
Post
curl -d 'username=test1&password=12345' https://web.cs.dal.ca/~gang/csci2133-project/step-db/login-rest- service.php [{"cus_num":11,"username":"test1","email":"test1@company.com"}]
15
CSCI 2133
curl -d @request.json -H 'Content-Type: application/json’ -X PUT http://localhost:8082/spring-rest/foos/9
curl -X DELETE http://localhost:8082/spring-rest/foos/9
If 401 – Unauthorized HTTP response code and an associated WWW-Authenticate header: curl --user baeldung:secretPassword http://example.com/
16
CSCI 2133
import os
But the result depends on work environment. Somehow exception happens, such as “curl command not found” Next.... Let us find elegant way.
17
CSCI 2133
From
curl -v https://web.cs.dal.ca/~gang/csci2133-project/step- db/login-all.php
To
import requests response = requests.get('https://web.cs.dal.ca/~gang/csci2133- project/step-db/login-all.php')
18
CSCI 2133
From
curl -d 'username=test1&password=12345' https://web.cs.dal.ca/~gang/csci2133-project/step-db/login-rest- service.php
To
import requests data = { 'username': 'test1', 'password': '12345' } response = requests.post('https://web.cs.dal.ca/~gang/csci2133- project/step-db/login-rest-service.php', data=data)
19
CSCI 2133
From
curl -X DELETE http://localhost:8082/spring-rest/foos/9
To
import requests response = requests.delete('http://localhost:8082/spring- rest/foos/9')
20
CSCI 2133
21
import requests data = { 'username': 'test1', 'password': '12345' } response = requests.post('https://web.cs.dal.ca/~gang/csc i2133-project/step-db/login-rest-service.php', data=data) print(response.json())
CSCI 2133
Generate Access Token to Authenticate ( aka Login) to Twitter API Once this is done you will need to get:
import base64 import requests client_key = ‘Y**********9' client_secret = 'Bsqx*********ExI' key_secret = '{}:{}'.format(client_key, client_secret).encode('ascii') b64_encoded_key = base64.b64encode(key_secret) b64_encoded_key = b64_encoded_key.decode('ascii')
22
CSCI 2133
endpoint to obtain a Bearer Token to be included in subsequent API requests.
base_url = 'https://api.twitter.com/' auth_url = '{}oauth2/token'.format(base_url) auth_headers = { 'Authorization': 'Basic {}'.format(b64_encoded_key), 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' } auth_data = { 'grant_type': 'client_credentials' } auth_resp = requests.post(auth_url, headers=auth_headers, data=auth_data, verify=False) print(auth_resp.json()) access_token = auth_resp.json()['access_token']
23
CSCI 2133
24
CSCI 2133
25 search_headers = { 'Authorization': 'Bearer {}'.format(access_token) } search_params = { 'q': 'General Election', 'result_type': 'recent', 'count': 2 } search_url = '{}1.1/search/tweets.json'.format(base_url) search_resp = requests.get(search_url, headers=search_headers, params=search_params, verify=False) tweet_data = search_resp.json() for x in tweet_data['statuses']: print(x['text'] + '\n')
CSCI 2133
26
CSCI 2133
27
CSCI 2133
import requests from django.http import HttpResponse def base(request):
data = {
'username’: request.GET[‘username’], 'password’: request.GET[‘password’]
} response = requests.post('https://web.cs.dal.ca/~gang/csci2133-project/step-db/login-rest-service.php', data=data) django_response = HttpResponse( content=response.content, status=response.status_code, content_type=response.headers['Content-Type'] )
return django_response
28
CSCI 2133
from django.http import HttpResponse def hello(request): text = """<h1>welcome to my app !</h1>""" return HttpResponse(text)
29
CSCI 2133
Example: request.GET[‘key’] / request.POST[‘key’]
Example: if request.method == ‘GET’
30
CSCI 2133
automatically by Django, HttpResponse objects are your responsibility. Usage:
from django.http import HttpResponse >>> response = HttpResponse("Here's the text of the Web page.") >>> response = HttpResponse("Text only, please.", content_type="text/plain")
31
CSCI 2133
from django.shortcuts import render def base(request): return render(request, “base.html", {})
32
CSCI 2133
33 import requests from django.http import HttpResponse from django.shortcuts import render def base(request): data = { 'username': request.GET.get('username'), 'password': request.GET.get('password') } response = requests.post('https://web.cs.dal.ca/~gang/csci2133-project/step- db/login-rest-service.php', data=data) respData = response.json() print(respData) html = render(request, 'base.html', {"theUser" : respData, "title": "track a user", "h2": "Search Result"}) return HttpResponse(html)
CSCI 2133
34
CSCI 2133
looks like the following: {{var|filters}}.
loop, template inheritance and more.
35
CSCI 2133
Example:
{% if theUser|length < 1 %} <h5>No Result!</h5> {% elif %} ….. {% endif %}
<table> {% for user in theUser %} <tr> {% for key,value in user.items %} <td> {{value}} </td> {% endfor %} </tr> {% endfor %} </table>
36
CSCI 2133
37
CSCI 2133
38
CSCI 2133
39
Pictures credit to https://djangobook.com/mdj2-models/
CSCI 2133
40
CSCI 2133
41
Pictures credit to https://djangobook.com/mdj2-models/
CSCI 2133
42
Pictures credit to https://djangobook.com/mdj2-models/
CSCI 2133
43
CSCI 2133
such as USER, PASSWORD, HOST must be added. For more details, see the reference documentation for DATABASES.
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'DB_NAME', 'USER': 'DB_USER', 'PASSWORD': 'DB_PASSWORD', 'HOST': 'localhost', # Or an IP Address that your DB is hosted on 'PORT': '3306', } }
You might want to install DB module if your python doesn’t have:
pip3 install mysqlclient If you fail command above, try old version: pip install mysqlclient==1.3.12
44
CSCI 2133
45
from django.db import models # Create your models here. class TeacherB0012345(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=50) province = models.CharField(max_length=2) email = models.EmailField(max_length=100, blank=True) class Meta: verbose_name_plural = 'Teacher' class CourseB0012345(models.Model): teacher = models.ForeignKey(TeacherB0012345, on_delete=models.CASCADE) name = models.CharField(max_length=42) code = models.CharField(max_length=4) website = models.URLField(max_length=200, null=True, blank=True) content = models.TextField() last_update = models.DateTimeField(auto_now_add=True)
CSCI 2133
python manage.py makemigrations
46
CSCI 2133
47
CSCI 2133
user="csci2133_gang", passwd="12345678",
48
CSCI 2133
host="db4free.net", user="csci2133_gang", passwd="12345678", database="csci2133_login“
Id int primary key Name varchar 50 Banner varchar 50 Homeaddress varchar 250 Emailaddress varchar 250
49
CSCI 2133