Why Use Modules?
Built-in Modules Example
import random
random.choice(["apple", "banana", "cherry", "durian"])
random.shuffle(["apple", "banana", "cherry", "durian"])
import random as omg_so_random
omg_so_random.choice(["apple", "banana", "cherry", "durian"])
omg_so_random.shuffle(["apple", "banana", "cherry", "durian"])
import random as r
r.choice(["apple", "banana", "cherry", "durian"])
r.shuffle(["apple", "banana", "cherry", "durian"])
Importing Parts of a Module
from MODULE import *
pattern
Different Ways to Import
import random
import random as omg_so_random
from random import *
from random import choice, shuffle
from random import choice as gimme_one, shuffle as mix_up_fruits
All of these work!
Custom Modules
Custom Modules
def fn():
return "do some stuff"
def other_fn():
return "do some other stuff"
Custom Modules Example
import file1
file1.fn() # 'do some stuff'
file2.fn() # 'do some other stuff'
file1.py
file2.py
External Modules
External Modules
pip
python3 -m pip install NAME_OF_PACKAGE
External Modules Example
Use the pyfiglet package!
The
__name__
Variable
__name__
import
Revisited
When you use import, Python...
Ignoring Code on Import
if __name__ == "__main__":
# this code will only run
# if the file is the main file!
HTTP Introduction
HTTP Introduction
The Internet
What Happens When...
Request/Response cycle
DNS Lookup
Like a Phonebook for the Internet!
DNS Server
google.com
172.217.9.142
facebook.com
157.240.2.35
amazon.com
54.239.17.6
Requests and Responses
Client
(e.g. your computer)
Server
172.217.9.142
<!doctype html>
<html lang="en">
<!--
HTML for google.com
will be here!
-->
</html>
GET /
200 OK
HTTP Headers
Header Examples
Response Headers
Request Headers
Response Status Codes
HTTP Verbs
GET
POST
APIs
Using the
requests
Module
requests
Module
Making a Request
import requests
response = requests.get("http://www.example.com")
Request Headers
import requests
response = requests.get(
"http://www.example.com",
headers={
"header1": "value1",
"header2": "value2"
}
)
What's a Query String?
Query String
# option 1
import requests
response = requests.get(
"http://www.example.com?key1=value1&key2=value2"
)
# option 2 - preferable!
import requests
response = requests.get(
"http://www.example.com",
params={
"key1": "value1",
"key2": "value2"
}
)
POST Request
import requests
import json
response = requests.post(
"http://www.example.com",
data=json.dumps({
"key1": "value1",
"key2": "value2"
})
)
A Note on APIs
Recap
if __name__ == "__main__"