TIL Python Basics Day 54 - Introduction to Web Development with HTTP & URL Routing / Command Line / Flask / Decorator

이다연·2021년 2월 8일
0

Udemy Python Course

목록 보기
50/64

What is Backend?

Client

when a user goes on to a browser, browser renders the webpage using server's response.

Server

Powerful computer hooked up to the internet 24/7, always ready to receive requests. Respond sending over HTML, CSS, JS, text, media files. Server fetches the data from the database and sends it to browser.

Database

Massive spread sheets relating to your website.

Analogy of restaurant.

Web Client <-> Web Server <-> Web Application Server (uWSGI, Gunicorn) <-> Database

Protocol: HTTP

http 코어 모듈은 클라이언트와 서버간 통신 규약. 서로 어떤식으로 데이터를 요청하고 보내줘야하는지 약속함. https is for security. 네트워크 관련 공부 필요.
e.g. ftp, smtp 등 다양한 종류의 프로토콜이 있음

IP Address : 127.0.0.1 == localhost

외부의 다른 컴퓨터가 아니라 컴퓨터 자기 자신을 나타내는 주소로 약속. 외부와 통신이 아니라, 내가 만든 서버 프로그램 테스트 위함

Port number 127.0.0.1:5000

클라이언트가 서버에 요청을 보내려고 할 때 서버에서 실행되고 있는 여러 프로그램 중 어느 프로그램과 통신할 것인지를 나타내기 위해 지정하는 번호.
서버에서 실행되고 있는 외부의 클라이언트 요청을 기다리는 프로그램들을 고유하게 식별하기 위한 번호

URL

Uniform Resource Locator

웹 상의 특정 자원의 위치를 나타낸 문자열. 특정 자원이란 HTML, CSS, JS, 이미지, 영상 파일 등.

URL structure

  • scheme: protocol name
  • host: specific server
  • path (/business/mart/item): locating the resource. There might not be an item file, server checkes database.
  • query (?category=14&id=2973): to specifiy the request

Domain Name

Text names are more familiar than numbers to human

  • Root domain: empty or . (dot)
  • Top level domain(TLD): country, service category e.g. .kr .gov
  • Second-level domain: e.g. google, naver
    and so on
    http://www.google.com == https://172.217.175.100
    google 이라는 이름을 가진 IP 주소를 가진 서버에 접속하는 것(상황에 따라 IP 주소는 달라짐)

Domain Name Resolution

Domain name(text) converted to IP address in a chain of process with help of Name Server.
Frequnetly used domain names cached for later use in my computer.

Common port numbers

http: 80
https: 443

Routing

route는 특정한 길로 보내다. 전송하다.
클라이언트가 요청한 URL에 맞게 서버에서 알맞은 응답을 해주려면, URL에 따라 알맞은 처리로 분기해주는 로직이 필요함. 이것을 라우팅이라고 함.

Command Line (module 446)

  • Kernel : In OS, refers to the actual program that interfaces with the hardware. Core of your OS.
    Window
  • ==Shell: User Interface.
    Two variants:
  1. GUI
  2. CLI (Command Line Interface)
  • Why use the command line?
    it's easier and fasater to control computer hardware.
    useful tool at your disposal ????

MacOS: spolight-Terminal hit enter
Window: default shell - start - search: command prompt / cmd

  • ~ (tilda): to home directory
  • pwd(print working directory): to locate where I am in my file path
  • ls(list)/ dir(window): list all of folders and files at your current working directory
  • cd(change directory) + tab button : e.g. cd Des (Desktop folder == 바탕화면)
    when I hit cd Des + tab button, it narrows down possible names, choose and hit enter
    -start . : opens GUI
  • cd.. : move to parent folder
  • mkdir(make directory): e.g. mkdir Test
  • rm -rf foldername(Mac): to delete the folder, we need to step up to parent folder. It will delete everything inside the folder (recursively, forcefully delete)
  • rmdir(Window)
rmdir /S practice
practice, Are you sure <Y/N>? Y
  • touch name.py: create a file
  • rm name.py: remove the file
  • exit
  • clear

Terminal is really powerful. Be extra careful when deleting and using it !!!!

=> google terminal cheatsheet, command line cheatsheet

table from Django Girls

Flask

create your First Web Server with Flask

Django와 같은 프레임워크를 사용하면, MVT 패턴이 적용된 틀 안에서 개발하면 되는데요. MVT 패턴이란 소프트웨어 아키텍처 패턴(Software Architecture Pattern) 중의 하나이고, 소프트웨어 아키텍처 패턴이란 무수히 많은 프로그램들의 다양한 동작 구조들을, 유사한 것들끼리 모으고 분류하여 정리한 여러 개의 패턴들을 의미합니다. MVT 패턴은 그중 하나로, 프로그램 내부에 크게 3가지 구성요소인 Model, View, Template이라는 단위가 존재하고, 이것들이 상호유기적으로 동작하는 패턴입니다. 그래서 Django로 개발을 하게 되면, 개발자는 Model, View, Template에 해당하는 각 부분만 코드로 잘 채워넣어주면 됩니다. 그럼 Django 프레임워크가 그것들을 연동시켜서 프로그램이 실행될 수 있게 해줍니다. 이렇게 일정한 패턴에 의존해서 개발하도록 하는 점은 Django 뿐만 아니라 다른 프레임워크들도 비슷합니다.(from codeit)

Framework

-a package of code
-Difference btw Library and Framwork: With Library, you are in full control when you call a method; however, with Framework, the code never calls into a framework, instead the framework calls you.

Install Flask

  1. click red bulb
  2. Preferences - Project - interpreter - "+" - search: Flask
  3. pip: from PyPi, copy the code, paste it terminal, hit enter
pip install Flask

Run server

Terminal
MacOS

$ export FLASK_APP=hello.py

Windows

set FLASK_APP=hello.py
flask run

Here is your website. I created a web server. It is created locally in our own computer. "http://127.0.0.1:5000/" This is the local address of our website.

This server is waiting for clients. If we run two flask applications to the same address, second one is not gonna run.

 (Press CTRL+C to quit)

__name__ & __main__

__name__ is used to check all the current class, functions, methods' name.
__main__ means it is run as a script, not a module which is used to import.
Script or Module?

From Flask class, to create Flask app, and in order to initialize, one required input is 'import name'

from flask import Flask

app = Flask(__name__)

Instead of using terminal, we can use standard control (green triangle) to run

if __name__ == "__main__":
    app.run()

@ Decorator

@ at sign
stackoverflow

  • If you want to add functionalities to each of functions without changing them.
  • Decorator is a function, which gives additonal functionality to existing function.
## Functions can have inputs/functionality/output
def add(n1, n2):
    return n1 + n2

def subtract(n1, n2):
    return n1 - n2

def multiply(n1, n2):
    return n1 * n2

def divide(n1, n2):
    return n1 / n2
  • Functions are first-class objects, can be passed around as arguments e.g. int/string/float etc.
def calculate(calc_function, n1, n2):
    return calc_function(n1, n2)

result = calculate(add, 2, 3)
print(result)
  • Functions can be nested in other functions
def outer_function():
    print("I'm outer")

    def nested_function():
        print("I'm inner")

    nested_function() #-> activating the function with ( )

outer_function()

#print 
I'm outer
I'm inner

  • Functions can be returned from other functions
def outer_function():
    print("I'm outer")

    def nested_function():
        print("I'm inner")

    return nested_function #-> notice no ( )
    
    inner_function = outer_function()
    inner_function()
-------------------------------------------

#1 into a variable, I will print "I'm outer", sets up a reference to the nested function.
and return output from nested_function.
What it will evaluate to is going to become nested_function.

inner_function = outer_function()
#print: I'm outer

#2 now add parenthesis to 'inner_function' variable
Basically, it added activator parenthesis () into output nested_function

inner_function = outer_function()
inner_function()
#print: 
I'm outer
I'm inner

Decorator details: Module 448, 449, 450

decorator_function can control calling of the function that was passed in.

def decorator_function(function):
  def wrapper_function(): #gonna trigger input function
    function() #input parameter
  return wrapper_function #Notice: no ()

e.g. repeated function: time.sleep()

def say_hello():
  time.sleep(2)
  print("Hello")

def say_bye():
  time.sleep(2)
  print("Bye")

def say_hey():
  time.sleep(2)
  print("Hey")

Decorator comes in handy

import time

def delay_decorator(function):
  def wrapper_function(): 
    time.sleep(2) 
    function() 
  return wrapper_function 
  
@delay_decorator  
def say_hello():
  print("Hello")
  
@delay_decorator 
def say_bye():
  print("Bye")

@delay_decorator 
def say_hey():
  print("Hey")


say_hello()
say_bye()
say_hey()
#print: it will all print all of them after 2 sec
  • Syntactic Sugar: added before or after function
def delay_decorator(function):
  def wrapper_function(): 
    #Do something before
    function()
    #Do something after
  return wrapper_function #no ()

e.g.

def delay_decorator(function):
  def wrapper_function(): 
    function() 
    print("You did it!")
  return wrapper_function 
  
def say_hey():
  print("Hey")
  
decorated_function = wrapper_function(say_hey)
decorated_function()

#print
Hey
You did it!

task. printing out the speed it takes to run the fast_function() vs the slow_function()

import time
current_time = time.time()
print(current_time)

def speed_calc_decorator(function):
    def wrapper_function():
        start_time = time.time()
        function()
        end_time = time.time()
        print(f"{function.__name__} run speed: {end_time - start_time}s")
    return wrapper_function

@speed_calc_decorator
def fast_function():
    for i in range(10000000):
        i * i
        
@speed_calc_decorator
def slow_function():
    for i in range(100000000):
        i * i
        
fast_function()
slow_function()

Routing

  • /: home
    When the user navigates to our URL with just a forward slash, they want to see homepage, so we are gonna show them Hello, World (from hello_world function)
  • Use the route() decorator to bind a function to a URL
    -route()is a decorator function which lives inside app object, from Flask class
@app.route('/') 
def hello_world():
    return 'Hello, World!'





word
available for one to use whenever or however one wishes.
"a helicopter was put at their disposal"

routing
the use of a particular path or direction for something to travel
"Logistics companies use computer-aided routing to maximize efficiency."

profile
Dayeon Lee | Django & Python Web Developer

2개의 댓글

comment-user-thumbnail
2024년 3월 29일

How does the backend communicate with the frontend or client-side?

답글 달기
comment-user-thumbnail
2024년 3월 29일

What are some popular backend frameworks used in web development? geometry dash subzero ask.

답글 달기