Day 054

AWESOMee·2022년 3월 30일
0

Udemy Python Bootcamp

목록 보기
54/64
post-thumbnail

Udemy Python Bootcamp Day 054

Backend Web Development with Python

What Exactly is the Backend?

Client, Server, Database

These three components together will determine how your backend will work.

  • Client
    This is the part that faces the user.
  • Server
    Always ready to receive requests over the internet.
  • Database
    Like a souped up spreadsheet where you are storing all the information related to your website.

Create Web Server with Flask

Flask is one of the most popular web development franeworks.

Framework is a little bit like a library in the sense that it's a package of code that you didn't write, but it also got some differences.
One of the biggest differences is the fact that a library is something which you call upon to do something specific. Whereas a framework is something which you have to abide by their rules, you have to use their architecture. And when it comes to triggering some sort of functionality, it's the framework that calls upon your code.

All we have to do is to plan ahead for certain situations.

from flask import Flask
app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'Hello, World!'

나의 너무 작고 소중한 Hello, World!

Understand the Command Line

The kernel refers to the actual program that interfaces with the hardware. So it's the core of your operating system.
The shall in computing refers to the user interface for you as a human to ba able to interact with the kernel and in turn with the hardware of your computer.
There's two variants to the shall. There are graphical user interface shells and there's also a command line interface. So this is an alternative way of interfacing with the kernel.

#Terminal

위치변경, 폴더 및 파일 생성/삭제 가능함
rm -rf를 이용한 삭제 시에는 특별히 주의할 것. bin에도 안남음..

Special Attribute built into Python

from flask import Flask

app = Flask(__name__)

print(__name__)

#output
__main__

This name is one of the special attributes that's built into Python. You could tap into the name to find out what is the current class, function, method, or descriptor's name.
And when we get main, what it's telling us is basically we're executing the code in a particular module. So, that means it's run as a script or from an interactive prompt, but it's not run from an imported module.

from flask import Flask

app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'Hello, World!'


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



Python Decorators

The syntax is code a Python decorator and this is something that you'll see in more advanced Python projects.

## 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()

outer_function()

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

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

    return nested_function

inner_function = outer_function()
inner_function()

The first-class objects, can be passed around as arguments e.g. int/string/float etc.

The ability for us to treat functions as first-class objects basically means that we can pass them around as if they were just any other argument.

The @ Syntax

## Simple Python Decorator Functions
import time

def delay_decorator(function):
    def wrapper_function():
        time.sleep(2)
        #Do something before
        function()
        function()
        #Do something after
    return wrapper_function

@delay_decorator
def say_hello():
    print("Hello")

#With the @ syntactic sugar
@delay_decorator
def say_bye():
    print("Bye")

#Without the @ syntactic sugar
def say_greeting():
    print("How are you?")
decorated_function = delay_decorator(say_greeting)
decorated_function()

#output
(after 2 seconds,)
How are you?
How are you?

from flask import Flask

app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'Hello, World!'

@app.route("/bye")
def say_bye():
    return "Bye"

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

Excercise

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

def speed_calc_decorator(function):
    def wrapped_function():
        start_time = time.time()
        function()
        end_time = time.time()
        duration = end_time - start_time
        function_name = function.__name__
        print(f"The {function_name} took {duration} seconds.")
    return wrapped_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()

사실 Instructions 읽고도 당최 뭘 하라는 건지 모르겠어서 솔루션 코드를 볼까 했지만 질의응답을 봤다..
대천사님께서 친히 솔루션 영상을 찍어서 올려놓아서 영상으로 이해함..
영상 먼저 본 후에 직접 작성해서 완성하긴 했는데
대천사님께서 실행했을 때는 0.9초, 6초 이런식이던데 나는 5초, 45초 나옴... 이렇게 속도차이 난다고...?

오 coding room에서는 더 빠르게 나옴

근데 왜 TypeError뜨는지 모르겠다..
멍청하다.. wrapped_function호출할때 ()붙이면 안되는데 붙여놓고 왜 타입에러 뜨는지 모르겠다니,,, 휴

암튼 오늘 배운 flask로 뭘할지 잘 모르겠지만,, 두고봐야겠죠. see ya~

profile
개발을 배우는 듯 하면서도

0개의 댓글