public:computer:python

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
public:computer:python [2021/08/02 18:39] alexpublic:computer:python [2023/01/02 15:20] (current) – [References] alex
Line 4: Line 4:
 ===== prepare ===== ===== prepare =====
  
 +==== on WSL2 ====
 +{{page>:public:computer:wsl#python_settings&noheader}}
 ==== get python ==== ==== get python ====
  
Line 15: Line 17:
     * <del>pyCharm</del>     * <del>pyCharm</del>
  
-<sxh bash>+<cli>
 $ python3 hello_world.py $ python3 hello_world.py
-</sxh>+</cli>
  
 ===== variables and types ===== ===== variables and types =====
Line 304: Line 306:
     """개를 모델화하는 시도"""  # docstring     """개를 모델화하는 시도"""  # docstring
          
-    def __init__(self, name, age):  # 생성자 메서드+    def __init__(self, name, age):  # 생성자 메서드, 반드시 구현
         ""name과 age 속성 초기화"""         ""name과 age 속성 초기화"""
         self.name = name         self.name = name
Line 320: Line 322:
 my_dog = Dog('Willie', 6) my_dog = Dog('Willie', 6)
 my_dog.sit() my_dog.sit()
-my_sog.roll_over()+my_dog.roll_over()
 </sxh> </sxh>
  
   * super() 메서드로 superclass에 접근   * super() 메서드로 superclass에 접근
   * override.   * override.
 +  * CamelCase
 +
 +
 +<sxh python>
 +from car import Car  # car.py 안에 Car 클래스 하나만 있을 경우
 +from car import ElectricCar  # car.py 안에 여러 클래스 중 ElectricCar 만 임포트
 +from car import Car, ElectricCar  # car.py 안에 Car, ElectricCar 클래스 임포트
 +import car  # car.py 안에 있는 모든 클래스 임포트
 +
 +from module_name import *
 +
 +from electric_car import ElectricCar as EC  # electric_car.py의 ElectricCar 클래스를 EC로 임포트
 +</sxh>
 +
 +  * python standard library
 +
 +<sxh python>
 +from random import randint
 +randint(1, 6)
 +
 +from random import choice
 +choiced_value = choice(list_values)
 +</sxh>
  
  
Line 330: Line 355:
 ===== file and exception ===== ===== file and exception =====
  
 +<sxh python>
 +# 기본적인 읽기
 +file_path = '/home/..../openfile.txt'
 +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 = 'pi_digits.txt'
 +with open(filename) as file_object:
 +    lines = file_object.readlines()
 +    
 +for line in lines:
 +    print(line.rstrip())
 +    
 +print(f"{pi_string[:52]..." # 52번째 캐릭터까지만
  
 +# write a file
 +filename = 'prg.txt'
  
 +with open(filename, 'w') as file_object:  # w: write mode, r: read mode, a: append mode, r+; read and write. default is 'r'
 +    file_object.write("I love programming.")
 +    
 +#open(filename, encoding='utf-8')
 +</sxh>
 +
 +
 +<sxh python>
 +try:
 +    print(5/0)
 +except ZeroDivisionError:  # FileNotFoundError,
 +    print("You can't divide by zero!")
 +    #pass  # 조용히 실패하기, except 블럭 안에 아무것도 하지 않고 pass만.
 +else:
 +    print("try block success.")
 +</sxh>
 +
 +  * string.replace(find_string, replace_string)
 +  * string.count(find_string) returns count
 +
 +
 +<sxh python>
 +import json
 +
 +json.dump(contents, file_object)  # contents를 file_object에 저장, with open(filename, 'w') 사용
 +loaded_object = json.load(file_object)  # with open(filename) 
 +</sxh>
 +
 +  * refactoring; 코드를 더 사용하기 쉽게 재구성
  
 ===== code test ===== ===== code test =====
 +  * unit test, 
 +  * test cases; unit test의 묶음
  
 +<sxh python>
 +import unittest
 +
 +class NamesTestCase(unittest.TestCase): #unittest.TestCase를 상속 받는 클래스 생성
 +
 +    def setUp(self):  # 각 메서드를 실행하기 전에 
 +....
 +....
 +    def test_first_last_name(self):
 +        ....
 +        ....
 +        self.assertEqual(formatted_name, 'Janis Joplin' # 예상한 결과가 일치하는 지 단언assert.
 +    
 +    
 +if __name__ == '__main__':  # 다른 프로그램에서 임포트하지 않고 직접 실행하면 __name__의 값은 '__main__'이 된다.
 +  unittest.main()
 +</sxh>
  
 +^ method  ^ example  ^
 +| assertEqual(a,b)  | a == b임을 확인  |
 +|assertNotEqual(a,b)  | a != b임을 확인  |
 +| assertTrue(x)  | x가 True임을 확인  |
 +| assertFalse(x)  | x가 False임을 확인  |
 +| assertIn(item, list)  | item이 list 안에 있음을 확인  |
 +| assertNotIn(item, list)  | item이 list 안에 있지 않음을 확인  |
  
  
 ===== game ===== ===== game =====
  
 +  * pygame
  
 +<cli>
 +$ python3 -m pip install --user pygame
 +</cli>
 +
 +<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,800))  # ((0,0), pygame.FULLSCREEN)
 +        pygame.display.set_caption("pygame")
 +        ...
 +        ...
 +        
 +        ...
 +        pygame.image.load('image/ship.bmp')
 +        ...
 +        
 +        ...
 +        for event in pygame.event.get():
 +            if event.type == pygame.QUIT:
 +                sys.exit()
 +            elif event.type == pygame.KEYDOWN:  # pygame.KEYUP, pygame.MOUSEBUTTONDOWN,
 +                if event.key == pygame.K_RIGHT:  # pygame.K_LEFT, pygame.K_q
 +                    ...
 +                     
 +            
 +        pygame.display.flip()
 +        
 +        # pygame.Rect(0, 0, self.settings.bullet_width,
 +        #     self.settings.bullet_height)
 +        # pygame.draw.rect(self.screen, self.color, self.rect)
 +        # pygame.sprite.Group()
 +        # pygame.sprite.goupcollide(
 +        #     self.bullets, self.aliens, True, True)
 +        # if pygame.sprite.spritecollideany(slef.ship, self.aliens):
 +        #     ...
 +        # mouse_pos = pygame.mouse.get_pos()
 +        # pygame.mouse.set_visible(False) / True
 +        # pygame.font.SysFont(None, 48)
 +        
 +</sxh>
 +
 +  * helper method; ex) _check_events(), _update_screen()
  
  
Line 347: Line 500:
 ===== data visualization ===== ===== data visualization =====
  
 +<cli>
 +$ python3 -m pip install --user matplotlib
 +</cli>
  
 +<sxh python>
 +import matplotlib.pyplot as plt
 +
 +squares = [1, 4, 9, 16, 25]
 +
 +plt.style.use('seaborn' # plt.style.available = ['seaborn-dark', 'seaborn-darkgrid', 'seaborn-ticks', 'fivethirtyeight', .... ]
 +fig, ax = plt.subplots()  # 그래프 생성
 +ax.plot(squares)  # ax.plot(squares, linewidth=3), ax.plot(input_values, squares, linewidth=3)
 +
 +ax.set_title("Square Numbers", fontsize=24)
 +ax.set_xlabel("Value", fontsize=14)
 +ax.set_ylabel("Square of Value", fontsize=14)
 +
 +ax.tick_params(axis='both', labelsize=14)  # 눈금 라벨 크기를 정함
 +
 +plt.show()
 +</sxh>
 +
 +  * ax.scatter(2, 4)
 +  * ax.scatter(2, 4, s=200)
 +  * ax.scatter(x_values, y_values, c='red', s=10)
 +  * ax.scatter(x_values, y_values, c=(0, 0.8, 0), s=10)
 +  * ax.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, s=10)
 +  * ax.tick_params(axis='both', which='major', labelsize=14)
 +  * ax.axis([0, 1100, 0, 11000000]
 +  * https://matplotlib.org
 +  * plt.savefig('squares_plot.png', bbox_inches='tight')
 +  * ax.get_xaxis().set_visible(False)
 +  * ax.get_yaxis().set_visible(False)
 +
 +<cli>
 +$ python3 -m pip install --user plotly
 +</cli>
 +
 +  * https://plot.ly/python
 +
 +
 +<sxh python>
 +from plotly.graph_objs import Bar, Layout
 +from plotly import offline
 +
 +...
 +...
 +data = [Bar(x=x_values, y=frequencies)]
 +...
 +
 +x_axis_config = {'title': 'Result'}
 +y_axis_config = {'title': 'Frequency of Result'}
 +my_layout = Layout(title='Results of rolling one D6 1000 times',
 +    xaxis_x_axis_config, yaxis=y_axis_config)
 +offline.plot({'data':data, 'layout': my_layout}, filename='d6.html')
 +</sxh>
 +
 +<sxh python>
 +import csv
 +
 +filename = 'data/aaa.csv'
 +
 +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, column_header)
 +...
 +</sxh>
 +
 +<sxh python>
 +import datetime import datetime
 +first_date = datetime.strptime('2021-08-02', '%Y-%m-%d')
 +print(first_date)
 +</sxh>
 +
 +  * [[https://strftime.org/|Python strftime cheatsheet]]
 +
 +  * ax.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1)
 +
 +
 +<cli>
 +$ python3 -m pip install --user requests
 +</cli>
 +
 +<sxh python>
 +import requests
 +
 +# API 호출을 보내고 응답을 저장
 +url = 'https://api.github.com/search/repositories?q=language:python&amp;sort=stars'
 +headers = {'Accept': 'application/vnd.github.v3+json'}
 +r = requests.get(url, headers=headers)
 +print(f"Status code: {r.status_code}")
 +
 +# API 응답을 변수에 저장
 +response_dict = r.json()
 +
 +# 결과 처리
 +print(response_dict.keys())
 +</sxh>
 +
 +  * 두 개의 그래프 그리기 -> 두 그래프 사이 칠하기
 +  * 에러 체크; except ValueError:
 +  * 세계 지도 만들기 -> 지도에 표시 -> 마커 크기 조절 -> 마커 색깔 -> 다른 컬러 스케일 -> 텍스트 추가 
 +  * 커스텀 툴팁 추가
 +  * 그래프에 클릭할 수 있는 링크 추가
  
  
Line 353: Line 613:
 ===== web application ===== ===== web application =====
  
 +==== virtual environment ====
 +<cli>
 +$ python3 -m venv ll_env  # ll_env란 이름으로 가상 환경 만들기
 +$ source ll_env/bin/activate  # ll_env의 가상 환경 활성화
 +(ll_env)$ deactivate  # ll_env 가상 환경 활성화 상태에서 사용 중지
 +</cli>
  
 +==== install django ====
 +<cli>
 +(ll_env)$ pip install django  # ll_env 가상 환경에서 장고 설치
 +(ll_env)$ django-admin startproject learning_log . # learning_log라는 이름으로 프로젝트 생성 마지막에 . 반드시 입력 -> learning_log 디렉토리 안에 settings.py, urls.py, wsgi.py 생성
 +(ll_env)$ python manage.py migrate  # 데이터베이스 생성 -> 기본적으로 db.sqlite3 생성
 +(ll_env)$ python manage.py startapp learning_logs  # learning_logs라는 이름의 앱 생성 -> model.py, admin.py, views.py
 +(ll_env)$ python manage.py runserver  # 프로젝트 실행
 +</cli>
  
 +==== 모델 정의 ====
 +<sxh python>
 +from django.db import models
  
 +class Topic(models.Model):
 +    """....."""
 +    ...
 +    def __str__(self):
 +        ...
 +        
 +</sxh>
  
 +  * settings.py 파일
 +<sxh python|settings.py>
 +INSTALLED_APPS = [
 +    # 내 앱
 +    'learning_logs',
 +    
 +    # 장고 기본 앱
 +    'django.contrib.admin',
 +    'django.contrib.auth',
 +    'django.contrib.contenttypes',
 +    'django.contrib.sessions',
 +    'django.contrib.messages',
 +    'django.contrib.staticfiles',
 +]
 +...
 +</sxh>
  
 +  * model을 수정하면 makemigrations를 먼저 실행하고 -> migrate 실행
 +<cli>
 +(ll_env)$ python manage.py makemigrations learning_logs
 +(ll_env)$ python manage.py migrate
 +</cli>
  
 +  * superuser 생성
 +<cli>
 +(ll_env)$ python manage.py createsuperuser
 +</cli>
  
 +  * 관리자 사이트에서 모델 등록
 +  * 주제 추가
 +
 +  * 장고 셸; quit to Ctrl-D or Ctrl-Z(on Windows)
 +<cli>
 +(ll_env)$ python manage.py shell
 +</cli>
 +
 +  * urls.py
 +<sxh python>
 +from django.contrib import admin
 +from django.urls import path
 +
 +urlpatterns = [
 +    path('admin/', admin.site.urls),
 +    path('', include('learning_logs.urls')),
 +]
 +</sxh>
 +
 +  * views.py
 +<sxh python>
 +from django.shortcuts import render
 +
 +# view here
 +</sxh>
 +
 +  * decorator; @login_required on views.py
 +
 +
 +  * other references;
 +    * bootstrap library
 +    * heroku; PaaS
 +    * Git;
 +
 +<cli>
 +(ll_env)$ pip install django-bootstrap4  # bootstrap4 설치
 +</cli>
 +
 +<cli>
 +(ll_env)$ pip install psycopg2==2.7.*
 +(ll_env)$ pip install django-heroku
 +(ll_env)$ pip install gunicorn
 +</cli>
 +
 +  * requirements.txt 파일; 작성한 프로젝트에 필요한 패키지들 모음
 +<cli>
 +(ll_env)$ pip freeze > requirements.txt
 +</cli>
 +
 +  * runtime.txt
 +<sxh>
 +python-3.7.2
 +</sxh>
 +
 +  * Procfile
 +<sxh>
 +web: gunicorn learning_log.wsgi --log-file -
 +</sxh>
 +
 +  * git
 +<cli>
 +(ll_env)$ git --version
 +</cli>
 +  * .gitignore
 +<sxh>
 +ll_env/
 +__pycache__/
 +*.sqlite3
 +</sxh>
 +
 +  * 헤로쿠 배포
 +    * 헤로쿠 계정
 +    * 헤로쿠 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://wikidocs.net/131351|098 고유한 식별자를 만들려면? ― uuid]]
 +    * <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))
 +</sxh>
  • public/computer/python.1627897186.txt.gz
  • Last modified: 2021/08/02 18:39
  • by alex