Differences
This shows you the differences between two versions of the page.
| Both sides previous revision Previous revision Next revision | Previous revision | ||
| public:computer:python [2021/08/02 18:39] – alex | public:computer:python [2023/01/02 15:20] (current) – [References] alex | ||
|---|---|---|---|
| Line 4: | Line 4: | ||
| ===== prepare ===== | ===== prepare ===== | ||
| + | ==== on WSL2 ==== | ||
| + | {{page>: | ||
| ==== get python ==== | ==== get python ==== | ||
| Line 15: | Line 17: | ||
| * < | * < | ||
| - | <sxh bash> | + | <cli> |
| $ python3 hello_world.py | $ python3 hello_world.py | ||
| - | </sxh> | + | </cli> |
| ===== variables and types ===== | ===== variables and types ===== | ||
| Line 304: | Line 306: | ||
| """ | """ | ||
| | | ||
| - | def __init__(self, | + | def __init__(self, |
| "" | "" | ||
| self.name = name | self.name = name | ||
| Line 320: | Line 322: | ||
| my_dog = Dog(' | my_dog = Dog(' | ||
| my_dog.sit() | my_dog.sit() | ||
| - | my_sog.roll_over() | + | my_dog.roll_over() |
| </ | </ | ||
| * super() 메서드로 superclass에 접근 | * super() 메서드로 superclass에 접근 | ||
| * override. | * override. | ||
| + | * CamelCase | ||
| + | |||
| + | |||
| + | <sxh python> | ||
| + | from car import Car # car.py 안에 Car 클래스 하나만 있을 경우 | ||
| + | from car import ElectricCar | ||
| + | from car import Car, ElectricCar | ||
| + | import car # car.py 안에 있는 모든 클래스 임포트 | ||
| + | |||
| + | from module_name import * | ||
| + | |||
| + | from electric_car import ElectricCar as EC # electric_car.py의 ElectricCar 클래스를 EC로 임포트 | ||
| + | </ | ||
| + | |||
| + | * python standard library | ||
| + | |||
| + | <sxh python> | ||
| + | from random import randint | ||
| + | randint(1, 6) | ||
| + | |||
| + | from random import choice | ||
| + | choiced_value = choice(list_values) | ||
| + | </ | ||
| Line 330: | Line 355: | ||
| ===== file and exception ===== | ===== file and exception ===== | ||
| + | <sxh python> | ||
| + | # 기본적인 읽기 | ||
| + | file_path = '/ | ||
| + | with open(file_path) as file_object: | ||
| + | contents = file_object.read() | ||
| + | | ||
| + | print(contents) | ||
| + | # 라인씩 읽기 | ||
| + | with open(filename) as file_object: | ||
| + | for line in file_object: | ||
| + | print(line) | ||
| + | | ||
| + | filename = ' | ||
| + | with open(filename) as file_object: | ||
| + | lines = file_object.readlines() | ||
| + | | ||
| + | for line in lines: | ||
| + | print(line.rstrip()) | ||
| + | | ||
| + | print(f" | ||
| + | # write a file | ||
| + | filename = ' | ||
| + | with open(filename, | ||
| + | file_object.write(" | ||
| + | | ||
| + | # | ||
| + | </ | ||
| + | |||
| + | |||
| + | <sxh python> | ||
| + | try: | ||
| + | print(5/0) | ||
| + | except ZeroDivisionError: | ||
| + | print(" | ||
| + | #pass # 조용히 실패하기, | ||
| + | else: | ||
| + | print(" | ||
| + | </ | ||
| + | |||
| + | * string.replace(find_string, | ||
| + | * string.count(find_string) returns count | ||
| + | |||
| + | |||
| + | <sxh python> | ||
| + | import json | ||
| + | |||
| + | json.dump(contents, | ||
| + | loaded_object = json.load(file_object) | ||
| + | </ | ||
| + | |||
| + | * refactoring; | ||
| ===== code test ===== | ===== code test ===== | ||
| + | * unit test, | ||
| + | * test cases; unit test의 묶음 | ||
| + | <sxh python> | ||
| + | import unittest | ||
| + | |||
| + | class NamesTestCase(unittest.TestCase): | ||
| + | |||
| + | def setUp(self): | ||
| + | .... | ||
| + | .... | ||
| + | def test_first_last_name(self): | ||
| + | .... | ||
| + | .... | ||
| + | self.assertEqual(formatted_name, | ||
| + | | ||
| + | | ||
| + | if __name__ == ' | ||
| + | unittest.main() | ||
| + | </ | ||
| + | ^ method | ||
| + | | assertEqual(a, | ||
| + | |assertNotEqual(a, | ||
| + | | assertTrue(x) | ||
| + | | assertFalse(x) | ||
| + | | assertIn(item, | ||
| + | | assertNotIn(item, | ||
| ===== game ===== | ===== game ===== | ||
| + | * pygame | ||
| + | <cli> | ||
| + | $ python3 -m pip install --user pygame | ||
| + | </ | ||
| + | |||
| + | <sxh python> | ||
| + | import sys | ||
| + | import pygame | ||
| + | import pygame.font | ||
| + | import pygame.sprite import Sprite | ||
| + | import pygame.sprite import Group | ||
| + | |||
| + | |||
| + | .... | ||
| + | pygame.init() | ||
| + | | ||
| + | pygame.display.set_mode((1200, | ||
| + | pygame.display.set_caption(" | ||
| + | ... | ||
| + | ... | ||
| + | | ||
| + | ... | ||
| + | pygame.image.load(' | ||
| + | ... | ||
| + | | ||
| + | ... | ||
| + | for event in pygame.event.get(): | ||
| + | if event.type == pygame.QUIT: | ||
| + | sys.exit() | ||
| + | elif event.type == pygame.KEYDOWN: | ||
| + | if event.key == pygame.K_RIGHT: | ||
| + | ... | ||
| + | |||
| + | | ||
| + | pygame.display.flip() | ||
| + | | ||
| + | # pygame.Rect(0, | ||
| + | # | ||
| + | # pygame.draw.rect(self.screen, | ||
| + | # pygame.sprite.Group() | ||
| + | # pygame.sprite.goupcollide( | ||
| + | # | ||
| + | # if pygame.sprite.spritecollideany(slef.ship, | ||
| + | # ... | ||
| + | # mouse_pos = pygame.mouse.get_pos() | ||
| + | # pygame.mouse.set_visible(False) / True | ||
| + | # pygame.font.SysFont(None, | ||
| + | | ||
| + | </ | ||
| + | |||
| + | * helper method; ex) _check_events(), | ||
| Line 347: | Line 500: | ||
| ===== data visualization ===== | ===== data visualization ===== | ||
| + | <cli> | ||
| + | $ python3 -m pip install --user matplotlib | ||
| + | </ | ||
| + | <sxh python> | ||
| + | import matplotlib.pyplot as plt | ||
| + | |||
| + | squares = [1, 4, 9, 16, 25] | ||
| + | |||
| + | plt.style.use(' | ||
| + | fig, ax = plt.subplots() | ||
| + | ax.plot(squares) | ||
| + | |||
| + | ax.set_title(" | ||
| + | ax.set_xlabel(" | ||
| + | ax.set_ylabel(" | ||
| + | |||
| + | ax.tick_params(axis=' | ||
| + | |||
| + | plt.show() | ||
| + | </ | ||
| + | |||
| + | * ax.scatter(2, | ||
| + | * ax.scatter(2, | ||
| + | * ax.scatter(x_values, | ||
| + | * ax.scatter(x_values, | ||
| + | * ax.scatter(x_values, | ||
| + | * ax.tick_params(axis=' | ||
| + | * ax.axis([0, 1100, 0, 11000000] | ||
| + | * https:// | ||
| + | * plt.savefig(' | ||
| + | * ax.get_xaxis().set_visible(False) | ||
| + | * ax.get_yaxis().set_visible(False) | ||
| + | |||
| + | <cli> | ||
| + | $ python3 -m pip install --user plotly | ||
| + | </ | ||
| + | |||
| + | * https:// | ||
| + | |||
| + | |||
| + | <sxh python> | ||
| + | from plotly.graph_objs import Bar, Layout | ||
| + | from plotly import offline | ||
| + | |||
| + | ... | ||
| + | ... | ||
| + | data = [Bar(x=x_values, | ||
| + | ... | ||
| + | |||
| + | x_axis_config = {' | ||
| + | y_axis_config = {' | ||
| + | my_layout = Layout(title=' | ||
| + | xaxis_x_axis_config, | ||
| + | offline.plot({' | ||
| + | </ | ||
| + | |||
| + | <sxh python> | ||
| + | import csv | ||
| + | |||
| + | filename = ' | ||
| + | |||
| + | with open(filename) as f: | ||
| + | reader = csv.reader(f) | ||
| + | header_row = next(reader) | ||
| + | print(header_row) | ||
| + | | ||
| + | for index, column_header in enumerate(header_row): | ||
| + | print(index, | ||
| + | ... | ||
| + | </ | ||
| + | |||
| + | <sxh python> | ||
| + | import datetime import datetime | ||
| + | first_date = datetime.strptime(' | ||
| + | print(first_date) | ||
| + | </ | ||
| + | |||
| + | * [[https:// | ||
| + | |||
| + | * ax.fill_between(dates, | ||
| + | |||
| + | |||
| + | <cli> | ||
| + | $ python3 -m pip install --user requests | ||
| + | </ | ||
| + | |||
| + | <sxh python> | ||
| + | import requests | ||
| + | |||
| + | # API 호출을 보내고 응답을 저장 | ||
| + | url = ' | ||
| + | headers = {' | ||
| + | r = requests.get(url, | ||
| + | print(f" | ||
| + | |||
| + | # API 응답을 변수에 저장 | ||
| + | response_dict = r.json() | ||
| + | |||
| + | # 결과 처리 | ||
| + | print(response_dict.keys()) | ||
| + | </ | ||
| + | |||
| + | * 두 개의 그래프 그리기 -> 두 그래프 사이 칠하기 | ||
| + | * 에러 체크; except ValueError: | ||
| + | * 세계 지도 만들기 -> 지도에 표시 -> 마커 크기 조절 -> 마커 색깔 -> 다른 컬러 스케일 -> 텍스트 추가 | ||
| + | * 커스텀 툴팁 추가 | ||
| + | * 그래프에 클릭할 수 있는 링크 추가 | ||
| Line 353: | Line 613: | ||
| ===== web application ===== | ===== web application ===== | ||
| + | ==== virtual environment ==== | ||
| + | <cli> | ||
| + | $ python3 -m venv ll_env | ||
| + | $ source ll_env/ | ||
| + | (ll_env)$ deactivate | ||
| + | </ | ||
| + | ==== install django ==== | ||
| + | <cli> | ||
| + | (ll_env)$ pip install django | ||
| + | (ll_env)$ django-admin startproject learning_log . # learning_log라는 이름으로 프로젝트 생성 마지막에 . 반드시 입력 -> learning_log 디렉토리 안에 settings.py, | ||
| + | (ll_env)$ python manage.py migrate | ||
| + | (ll_env)$ python manage.py startapp learning_logs | ||
| + | (ll_env)$ python manage.py runserver | ||
| + | </ | ||
| + | ==== 모델 정의 ==== | ||
| + | <sxh python> | ||
| + | from django.db import models | ||
| + | class Topic(models.Model): | ||
| + | """ | ||
| + | ... | ||
| + | def __str__(self): | ||
| + | ... | ||
| + | | ||
| + | </ | ||
| + | * settings.py 파일 | ||
| + | <sxh python|settings.py> | ||
| + | INSTALLED_APPS = [ | ||
| + | # 내 앱 | ||
| + | ' | ||
| + | | ||
| + | # 장고 기본 앱 | ||
| + | ' | ||
| + | ' | ||
| + | ' | ||
| + | ' | ||
| + | ' | ||
| + | ' | ||
| + | ] | ||
| + | ... | ||
| + | </ | ||
| + | * model을 수정하면 makemigrations를 먼저 실행하고 -> migrate 실행 | ||
| + | <cli> | ||
| + | (ll_env)$ python manage.py makemigrations learning_logs | ||
| + | (ll_env)$ python manage.py migrate | ||
| + | </ | ||
| + | * superuser 생성 | ||
| + | <cli> | ||
| + | (ll_env)$ python manage.py createsuperuser | ||
| + | </ | ||
| + | * 관리자 사이트에서 모델 등록 | ||
| + | * 주제 추가 | ||
| + | |||
| + | * 장고 셸; quit to Ctrl-D or Ctrl-Z(on Windows) | ||
| + | <cli> | ||
| + | (ll_env)$ python manage.py shell | ||
| + | </ | ||
| + | |||
| + | * urls.py | ||
| + | <sxh python> | ||
| + | from django.contrib import admin | ||
| + | from django.urls import path | ||
| + | |||
| + | urlpatterns = [ | ||
| + | path(' | ||
| + | path('', | ||
| + | ] | ||
| + | </ | ||
| + | |||
| + | * views.py | ||
| + | <sxh python> | ||
| + | from django.shortcuts import render | ||
| + | |||
| + | # view here | ||
| + | </ | ||
| + | |||
| + | * decorator; @login_required on views.py | ||
| + | |||
| + | |||
| + | * other references; | ||
| + | * bootstrap library | ||
| + | * heroku; PaaS | ||
| + | * Git; | ||
| + | |||
| + | <cli> | ||
| + | (ll_env)$ pip install django-bootstrap4 | ||
| + | </ | ||
| + | |||
| + | <cli> | ||
| + | (ll_env)$ pip install psycopg2==2.7.* | ||
| + | (ll_env)$ pip install django-heroku | ||
| + | (ll_env)$ pip install gunicorn | ||
| + | </ | ||
| + | |||
| + | * requirements.txt 파일; 작성한 프로젝트에 필요한 패키지들 모음 | ||
| + | <cli> | ||
| + | (ll_env)$ pip freeze > requirements.txt | ||
| + | </ | ||
| + | |||
| + | * runtime.txt | ||
| + | <sxh> | ||
| + | python-3.7.2 | ||
| + | </ | ||
| + | |||
| + | * Procfile | ||
| + | <sxh> | ||
| + | web: gunicorn learning_log.wsgi --log-file - | ||
| + | </ | ||
| + | |||
| + | * git | ||
| + | <cli> | ||
| + | (ll_env)$ git --version | ||
| + | </ | ||
| + | * .gitignore | ||
| + | <sxh> | ||
| + | ll_env/ | ||
| + | __pycache__/ | ||
| + | *.sqlite3 | ||
| + | </ | ||
| + | |||
| + | * 헤로쿠 배포 | ||
| + | * 헤로쿠 계정 | ||
| + | * 헤로쿠 cli 설치 | ||
| + | * 필수 패키지 설치 | ||
| + | * requirements.txt 생성 | ||
| + | * 파이썬 런타임 명시; runtime.txt | ||
| + | * 헤로쿠에서 쓸 수 있도록 settings.py 수정 | ||
| + | * Procfile 만들기 | ||
| + | * git을 사용해 프로젝트 파일 추적; 깃 설치 -> 설정 -> .gitignore 생성 -> 프로젝트 커밋 | ||
| + | * 헤로쿠에 올리기 | ||
| + | * 헤로쿠 데이터 베이스 세팅 | ||
| + | * 헤로쿠 배포 과정 개선; 헤로쿠에 슈퍼유저 생성 -> 사용하기 쉬운 url 만들기 | ||
| + | * 프로젝트 보안; settings.py의 DEBUG 플래그 설정 | ||
| + | * 커밋과 푸시 | ||
| + | * 헤로쿠에서 환경 변수 세팅하기 | ||
| + | * 커스텀 에러 페이지 만들기; 커스텀 템플릿 만들기 -> 로컬에서 에러 페이지 보기 -> 헤로쿠에 변경 내용 올리기 -> get_object_or_404() 메서드 | ||
| + | * SECRET_KEY 세팅 | ||
| + | * 헤로쿠에서 프로젝트 삭제 | ||
| + | |||
| + | |||
| + | ===== Python Keywords and internal functions ===== | ||
| + | ==== keywords ==== | ||
| + | * False | ||
| + | * None | ||
| + | * True | ||
| + | * and | ||
| + | * as | ||
| + | * assert | ||
| + | * async | ||
| + | * await | ||
| + | * break | ||
| + | * class | ||
| + | * continue | ||
| + | * def | ||
| + | * del | ||
| + | * elif | ||
| + | * else | ||
| + | * except | ||
| + | * finally | ||
| + | * for | ||
| + | * from | ||
| + | * global | ||
| + | * if | ||
| + | * import | ||
| + | * in | ||
| + | * is | ||
| + | * lambda | ||
| + | * nonlocal | ||
| + | * not | ||
| + | * or | ||
| + | * pass | ||
| + | * raise | ||
| + | * return | ||
| + | * try | ||
| + | * while | ||
| + | * with | ||
| + | * yield | ||
| + | |||
| + | ==== python internal functions ==== | ||
| + | * abs() | ||
| + | * all() | ||
| + | * any() | ||
| + | * ascii() | ||
| + | * bin() | ||
| + | * bool() | ||
| + | * breakpoint() | ||
| + | * bytearray() | ||
| + | * bytes() | ||
| + | * callable() | ||
| + | * chr() | ||
| + | * classmethod() | ||
| + | * compile() | ||
| + | * complex() | ||
| + | * delattr() | ||
| + | * dict() | ||
| + | * divmod() | ||
| + | * enumerate() | ||
| + | * eval() | ||
| + | * exec() | ||
| + | * filter() | ||
| + | * float() | ||
| + | * format() | ||
| + | * frozenset() | ||
| + | * getattr() | ||
| + | * globals() | ||
| + | * hasattr() | ||
| + | * hash() | ||
| + | * help() | ||
| + | * hex() | ||
| + | * id() | ||
| + | * input() | ||
| + | * int() | ||
| + | * isinstance() | ||
| + | * issubclass() | ||
| + | * iter() | ||
| + | * len() | ||
| + | * list() | ||
| + | * locals() | ||
| + | * map() | ||
| + | * max() | ||
| + | * memoryview() | ||
| + | * min() | ||
| + | * next() | ||
| + | * object() | ||
| + | * oct() | ||
| + | * open() | ||
| + | * ord() | ||
| + | * pow() | ||
| + | * print() | ||
| + | * property() | ||
| + | * range() | ||
| + | * repr() | ||
| + | * reversed() | ||
| + | * round() | ||
| + | * set() | ||
| + | * setattr() | ||
| + | * slice() | ||
| + | * sorted() | ||
| + | * staticmethod() | ||
| + | * str() | ||
| + | * sum() | ||
| + | * super() | ||
| + | * tuple() | ||
| + | * type() | ||
| + | * vars() | ||
| + | * zip() | ||
| + | * __import__() | ||
| + | |||
| + | ===== References ===== | ||
| + | * [[https:// | ||
| + | * <sxh python> | ||
| + | import uuid | ||
| + | strLongUUID = uuid.uuid1() | ||
| + | print(strLongUUID) | ||
| + | print(strLongUUID.bytes) | ||
| + | print(strLongUUID.hex) | ||
| + | print(strLongUUID.int) | ||
| + | print(strLongUUID.fields) | ||
| + | print(strLongUUID.urn) | ||
| + | print('' | ||
| + | |||
| + | #pip install shortuuid | ||
| + | import shortuuid | ||
| + | strShortUUID = shortuuid.uuid() | ||
| + | print(strShortUUID) | ||
| + | print(len(strShortUUID)) | ||
| + | </ | ||