StoryCode

'Python, 파이썬'에 해당되는 글 29건

  1. 기본문법
  2. DJango (Windows)
  3. 설치.DJango + Redis + Celery
  4. 설치.Windows10.Request Module
  5. Reference
  6. 설치
  7. Manage Excel
  8. 파이썬 설치시
  9. Python 3.6.5 Release

기본문법

Python, 파이썬
반응형

기본문법 참조 1) https://wikidocs.net/20

추가 참조 2) https://ssungkang.tistory.com/entry/%ED%81%B4%EB%9E%98%EC%8A%A4%EC%99%80-%EC%9D%B8%EC%8A%A4%ED%84%B4%EC%8A%A4%EB%9E%80-3-%EB%A9%94%EC%86%8C%EB%93%9C?category=310107



데이타 타입

 

 

True / False
참조) https://edykim.com/ko/post/python-list-vs.-tuple/

List = [1, 2, 3]
Tuple = ( 1, 2, 3 )
# 둘의 차이는 List 는 가변적, 튜플은 불변적이다.
# List[1] = "two" 를 하면 결과 [ 1, 'two', 3 ] 이 출력된다.
# Tuple[1] = "two" 하면 오류가 난다.
# 즉 List 에는 .append() 할 수 있지만, Tuple 은 안된다.

dict 타입)
mydata = {
    "name" : "hongildong",
    "info" : [
        "address":"seoul",
        "age" : "30"
    ]
}

dict => json string

myjson = json.dumps(mydata)

x = (1,2,3)

print (1 in x) # True

print (2 in x) # False

fruit = ["사과", "사과", "바나나", "사과", "사과", "바나나", "사과", "사과","바나나", "복숭아"]
countfruit = {}

for fruitname in fruit:
    if fruitname in countofruit:
        countfruit[ fruitname ] = countfruit[ fruitname ]+1
    else:
        countfruit[ fruitname ] = 1

print (d)


# {'사과':5, '바나나':3, '복숭아':1}

기본 문장

1)
money = 1000
if money >= 10000:
   print ("Yes")
else:
   print("No")

2)
if money >= 100 and money <= 10000 or money == 0:
if not 0:

if 1 in [1,2,3]

if a in ('a', 'b', 'c')

3)
message = "success" if score >= 60 else "failure"

변수 스코프

Local   :   함수 내부의 공간
Enclosing Function Local   :  함수를 내포하는 또 다른 함수의 공간
Global   :   함수 외부의 공간
Built-in   :   내장영역

x = 10
y = 20
def outer():
    x = 11
    def inner():
        z = 30
        print(x,y,z)
    inner()
    x = 40
    inner()
    global y
    y = 30


outer()
print (x)
print (y)

# 11 20 30
# 40 20 30
# 10
# 30

 정규식

https://stackoverflow.com/questions/1185524/how-do-i-trim-whitespace 
# 양쪽 공백 제거
s = " \t a string example\t "
s = s.strip()

# 오른쪽 공백 제거
s = s.rstrip()

# 왼쪽 공백 제거
s = s.lstrip()

# 정규식
import re
pat = re.compile(r'\s+')
s = '   \t   foo   \t   bar   \t   '
print pat.sub('', s) # prints "foobar"

출처: https://bluesid.tistory.com/337 [기록, 정리 조각]
Class 정의 class Human():
    def __init__(self):
        print("초기화 함수가 실행되었습니다.")

    def __str__(self): # to_string()
        return "현재 {}의 나이는 {}세 입니다.".format(self.job,self.age)

    def define_Human(job,age):
        person = Human()
        person.job = job
        person.age = age
        return person
 
    def get_older(self):
        self.age += 1
        print("{}의 나이가 {}가 되었습니다".format(self.job,self.age))

    def speak(self, message):
        print(message)

class Police(Human):
    def arrest(self, tohuman):
       print("체포 : " + tohuman)

person = Human.define_Human('student',23)
arrestperson = Police()



#person.get_older() # student의 나이가 24가 되었습니다

Package

 

# Package 는 directory 다.

main.py

> animal
   __init__.py : Package 에 들어있어야 하는 필수 파일이다. 내용으로 from class명 import funcion명
   cat.py  : cat class 파일이다.
   dog.py : dog class 파일이다.


참조) animal.__init__py 의 내용
from .cat import Cat
from .dog import Dog

Static method
Instance Method
Class

Meta Class

 
Static Method : 일반적인 Class 의 Static Method
Instance Method : 일반적인 Instance Method
Class : 일반적인 Class

Meta Class : 동적 클래스 생성. API 제작용. 파이썬에서는 클래스 자체가 객체이며, 클래스를 만드는 역할이 메타 클래스. Type = 'type'.

Meta Class 추가설명 참조 : https://dojang.io/mod/page/view.php?id=2468

선언 방법 예 1)
myClass = type('myClass', (), '{'a':True}}

* 위 문장은 아래 클래스 정의와 같다.
class myClass(object):
    a = True

선언후 클래스 할당1)
    myclassinstance = myClass()






선언 방법 예 2)
def replace(self, old, new):    # 클래스에 들어갈 메서드 정의
    while old in self:
        self[self.index(old)] = new
 
# list를 상속받음, 속성 desc, 메서드 replace 추가
AdvancedList = type('AdvancedList', (list, ), { 'desc': '향상된 리스트', 'replace': replace })
 
x = AdvancedList([1, 2, 3, 1, 2, 3, 1, 2, 3])
x.replace(1, 100)
print(x)         # [100, 2, 3, 100, 2, 3, 100, 2, 3]
print(x.desc)    # 향상된 리스트





선언 방법 예 3) 클래스가 type 을 상속 받으면 메타 클래스가 된다. Ex> class metaclass(type):
class MakeCalc(type):    # type을 상속받음
    def __new__(metacls, name, bases, namespace):      # 새 클래스를 만들 때 호출되는 메서드
        namespace['desc'] = '계산 클래스'              # 새 클래스에 속성 추가
        namespace['add'] = lambda self, a, b: a + b    # 새 클래스에 메서드 추가
        return type.__new__(metacls, name, bases, namespace)    # type의 __new__ 호출
 
Calc = MakeCalc('Calc', (), {})    # 메타클래스 MakeCalc로 클래스 Calc 생성
c = Calc()                         # 클래스 Calc로 인스턴스 c 생성
print(c.desc)                      # '계산 클래스': 인스턴스 c의 속성 출력
print(c.add(1, 2))                 # 3: 인스턴스 c의 메서드 호출







활용)
class Singleton(type):    # type을 상속받음
    __instances = {}      # 클래스의 인스턴스를 저장할 속성
    def __call__(cls, *args, **kwargs):    # 클래스로 인스턴스를 만들 때 호출되는 메서드
        if cls not in cls.__instances:     # 클래스로 인스턴스를 생성하지 않았는지 확인
            cls.__instances[cls] = super().__call__(*args, **kwargs)
                                           # 생성하지 않았으면 인스턴스를 생성하여 속성에 저장
        return cls.__instances[cls]        # 클래스로 인스턴스를 생성했으면 인스턴스 반환
 
class Hello(metaclass=Singleton):    # 메타클래스로 Singleton을 지정
    pass
 
a = Hello()     # 클래스 Hello로 인스턴스 a 생성
b = Hello()     # 클래스 Hello로 인스턴스 b 생성
print(a is b)   # True: 인스턴스 a와 b는 같음
언패킹 ( Unpacking ) Case 1)
def mysum(a,b):
    result = a+b
    return result

mylist = [3,5]

print(mysum(*mylist)) # 8
Case 2)
def mysum(*args):
    result = 0
    for num in args:
        result = result + num
    return result

mylist = [3,5,7]

print(mysum(*mylist)) # 15
키워드 인수 def subject(math, english, korean):
    print('수학 성적: ', math)
    print('영어 성적: ', english)
    print('국어 성적: ', korean)

subject(90,85,70)subject(90,85,70)
#수학 성적:  90
#영어 성적:  85
#국어 성적:  70

subject(english=85,korean=70,math=90)
#수학 성적:  90
#영어 성적:  85
#국어 성적:  70
"딕셔너리 + 키워드 인수" 언패킹 def subject(math, english, korean):
    print('수학 성적: ', math)
    print('영어 성적: ', english)
    print('국어 성적: ', korean)

myscore = {'english': 85, 'korean': 70, 'math': 90}
subject(**myscore)
#수학 성적:  85  
#영어 성적:  70  
#국어 성적:  90

-------------------------------------------------------------------------

def subject(math, english, korean):
    print('수학 성적: ', math)
    print('영어 성적: ', english)
    print('국어 성적: ', korean)

myscore = {'english': 85, 'korean': 70, 'math': 90}
subject(*myscore)
#수학 성적:  english
#영어 성적:  korean
#국어 성적:  math

-------------------------------------------------------------------------

def subject(**kwargs):
    for key,value in kwargs.items():
        print(key+' 성적: ', value)


myscore = {'english': 85, 'korean': 70, 'math': 90}
subject(**myscore)
@decorator

데코레이터

https://ssungkang.tistory.com/entry/python-%EC%9E%A5%EC%8B%9D%EC%9E%90-%EB%8D%B0%EC%BD%94%EB%A0%88%EC%9D%B4%ED%84%B0decorator-%EB%A5%BC-%EC%95%8C%EC%95%84%EB%B3%B4%EC%9E%90?category=310107

문자열함수 a = "ssungkang"
 
print (a.index("k")) # 5
print (a.find("k"))  # 5
print (a.index("x")) # error
print (a.find("x"))  # -1
자료 처리.map test = [1,2,3,4]
 
def func(x):
    return x * 2
 
print(list(map(func, test)))
 
# [2, 4, 6, 8]
자료 처리.String.문자열.Character split test = input().split()
print(test)
#['1', '2', '3', '4']

for i in range(len(test)):
    test[i] = int(test[i])
print(test)
# [1, 2, 3, 4]


위 두 문장을 하나로 합치면,
test = list(map(int, input().split()))
print(test)
# [1, 2, 3, 4]
외부 모듈 사용하기

Ex>

cmd> pip install geopy

 

python>

import from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="wonie")
location = geolocator.geocode("175 5th Avenue NYC")
print (location)

반응형

'Python, 파이썬' 카테고리의 다른 글

DJango.ORM  (0) 2020.02.12
Django Rest FrameWork  (0) 2020.02.07
DJango (Windows)  (0) 2020.01.31
설치.DJango + Redis + Celery  (0) 2020.01.29
설치.Windows10.Request Module  (0) 2019.08.06

DJango (Windows)

Python, 파이썬
반응형

 

  터미널 명령 결과
1 Terminal ( git bash ) $ mkdir proejctname
code proejctname
프로젝트용 폴더 생성
VisualCode 로 proejctname 오픈
2 VSC Terminal ( powershell ) $
단축키 : Ctrl + `
(VSC > View > Terminal )
python -m venv myvenv 가상환경 생성됨.
3 VSC Terminal ( git bash ) $ source myvenv/Scripts/activate (venv) 진입
4 VSC Terminal ( git bash, venv ) $ pip install django
pip install pylint-django
venv 를 생성후, venv내에 프로젝트에 적합한 개발환경인 django 구축.
5 VSC Terminal ( git bash, venv ) $ django-admin startproject myproject myproject 라는 "django 프로젝트" 생성
그 아래 myproject 폴더와 manage.py 생성
6 VSC Terminal ( gitbash, venv ) myproject $ python manage.py startapp myapp 프로젝트내에 앱이 만들어 진다.
여러 앱을 만들수 있으나 단일앱으로 해본다.

앱을 프로젝트 연결 : myproject/myproject/settings.py 의 INSTALLED_APPS 에 myapp.apps.MyappConfig추가 
( 추가 규칙 : '{app이름}.apps.{app이름(맨 앞이 대문자)}Config')
= myapp/apps.py 의 class 명임.

7 VSC Terminal ( gitbash, venv ) my project $ mkdir myapp/templates settings.py > TEMPLATES > DIRS 에 
os.path.join(BASE_DIR, '/templates'), 추가
8 VSC Terminal ( git bash, venv ) my project $ python manage.py runserver http://127.0.0.1:8000 으로 장고 접속 가능
9.1 VSC Terminal ( git bash, venv ) my project $ python manage.py makemigrations settings.py > DATABASES 에 있는 NAME 으로 "빈 DB 파일" 을 생성 (sqlite3)
9.2 VSC Terminal ( git bash, venv ) my project $ python manage.py migrate 9.1의 빈 DB 파일에 실제 Meta Table과 Table 생성
9.3 VSC Terminal ( git bash, venv ) my project $ python manage.py createsuperuser 9.2 DB 파일에 접근할 계정 생성

설치

참조) https://ssungkang.tistory.com/entry/Django-01-%EA%B8%B0%EB%B3%B8%ED%99%98%EA%B2%BD%EC%85%8B%ED%8C%85-%EA%B0%80%EC%83%81%ED%99%98%EA%B2%BD-%EB%A7%8C%EB%93%A4%EA%B8%B0?category=320582

 

1. git-scm.com 에서 git 설치후, 시작메뉴에서 git bash 실행

 

2. 가상 환경용 디렉토리 생성 (0000-000,Project.Dev.Repository\Dev.Django\)

gitbash$ mkdir Django

gitbash$ mkdir Django/venvproject

gitbash$ cd Django

 

3.vscode 사용 편의를 위해 "$ code 프로젝트폴더명" 를 실행할 수 있도록 하면 편한데,

vscode 설치후, 환경변수 PATH에 "Microsoft VS Code" 디렉토리를 추가하면 된다.

 

4.vscode 실행

gitbash$ code venvproject/

 

5.python 설치

Ctrl + Shift + X 를 눌러서 Python 을 검색후 설치한다.

 

6.Shell 추가

Ctrl + Shift + P 를 눌러서, Terminal: Select Default Shell 을 입력후, Git Bash 를 선택한다.

Menu > Terminal > New Terminal 을 클릭하면, bash 를 선택할 수 있게 된다.

( 반드시 새 터미널을 열어야 한다 )

 

7.가상환경생성

vscode menu > Terminal > New Terminal 를 클릭한뒤,

terminal 1:powershell> python3 -m venv myvenv 실행. ( myvenv 는 사용자가 자유로이 명명. VSCode 왼쪽 EXPLORER>VENVPROJECT>myvenv 가 생성되니 눈으로 확인 )

 

8.가상환경 실행

terminal 2:gitbash> source myvenv/Scripts/activate 실행

명령 실행후 프롬프트에 (myvenv) 가 앞에 나와야 한다.

 

source 문장을 실행했는데, "cmdlet, 함수, 스크립트..." 라는 오류가 발생하면, https://itinerant.tistory.com/63 참조

혹은 위 6번 다시 참조.

 

9.django 설치

(myvenv) $ pip install django

 

 

 

 

 

 

 

 

 

 

 

Hello, World

참조) https://ssungkang.tistory.com/entry/Django-02-Django-%EC%8B%9C%EC%9E%91-Hello-World-%EC%B6%9C%EB%A0%A5?category=320582

 

 

1. Project 만들기

django-admin startproject myproject

cd myproject

 

2. 서버 실행

python manage.py runserver

 

3. http 접속해서 확인 가능

http://127.0.0.1:8000/

 

4. 앱생성

python manage.py startapp myapp

- myproject프로젝트에 myapp 폴더가 생성됨

 

- 앱을 프로젝트와 연결해줘야 함

myproject/myproject/settings.py

INSTALLED_APPS = [

    'django.contrib.admin',

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.messages',

    'django.contrib.staticfiles',

    'myapp.apps.MyappConfig'

]

의 INSTALLED_APPS 에 myapp.apps.MyappConfig추가 ( 추가 규칙 : '{app이름}.apps.{app이름(맨 앞이 대문자)}Config')

 

- 디렉토리 연결 :

myproject/myproject/settings.py

TEMPLATES = [

    {

        'BACKEND''django.template.backends.django.DjangoTemplates',

        'DIRS': [os.path.join(BASE_DIR, '/templates'),],

 

5. 화면에 보여질 html 파일과 views.py 에 home.html 함수 만들기

- myapp에 templates 라는 디텍토리를 만들고 필요한 만큼, templates 디렉토리안에 home.html 을 만든다.

 

myapp/templates/home.html

<h1>Hello World </h1>

 

myapp/views.py

from django.shortcuts import render

def home(request):

    return render(request, 'home.html')

 

6.  url 연결.

- url 로 접근시, views.py 에 있는 함수를 실행시키고, 그 함수가 html 파일을 띄워준다.

 

myprojects/urls.py에 추가할 내용

import myapp.views

urlpatterns = [

   path('', myapp.views.home, name='home'), // 참고 : '' 면 http://127.0.0.1:8080/ root가 된다.

]

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

단어수 세는 프로그램

참조) https://ssungkang.tistory.com/entry/Django-03-%EB%8B%A8%EC%96%B4-%EC%88%98-%EC%84%B8%EB%8A%94-%ED%94%84%EB%A1%9C%EC%A0%9D%ED%8A%B8?category=320582

 

 

참고)

아래 urls.py 의 path 중 name='home' 에 적힌 부분은,

그 아래 있는 about.html 의 <a href="{%url 'home'%}"> 에서 사용된다.

 

 

 

#urls.py

urlpatterns = [

    path('admin/', admin.site.urls),

 

    path('',       wordcount.views.home,  name='home'),

    path('about/', wordcount.views.about, name='about'),

]

 

 

 

 

#about.html

<h1>ABOUT 페이지</h1>

<p>글자 수를 셀 수 있는 페이지입니다.</p>

<a href="{%url 'home'%}">HOME</a> <= urls.py 의 path 에 정의된 name 이다.

 

 

 

 

 

 

# views.py

from django.shortcuts import render

 

from django.shortcuts import render

def home(request):

    return render(request, 'home.html')

 

def about(request):

    return render(request, 'about.html')

 

def result(request):

    full = request.GET['fulltext']

    words = full.split()

    words_dic = {}

    for word in words:

        if word in words_dic:

            words_dic[word] += 1

        else:

            words_dic[word] = 1

    return render(request, 'result.html', {'full':full,'length':len(words),'dic':words_dic.items()})

 

 

 

 

 

 

#result.html

<h1>총 단어 수:</h1>

<a href="{%url 'home'%}">HOME</a><br/>

<h2>입력한 텍스트 : </h2>

{{full}} <= views.py 에서 result 함수내 return 문장에 적힌 full 을 의미한다.

<h2>단어 카운트 : </h2>

{% for key,value in dic %}

{{key}} : {{value}}

<br/>

{% endfor %}

 

 

 

 

 

 

 

필터

# 참조 : https://django-doc-test-kor.readthedocs.io/en/old_master/ref/templates/builtins.html#ref-templates-builtins-filters

 

{{ value|add:"2" }} => Ex> "value = 4, add 2" == 6

{{ first|add:second }} => Ex> "first = {1,2,3}, add second={4,5,6}" == {1,2,3,4,5,6}

 

 

 

 

 

 

 

태그

# 참조 : https://django-doc-test-kor.readthedocs.io/en/old_master/ref/templates/builtins.html#ref-templates-builtins-tags

 

 

 

 

 

 

 

 

 

 

명령문

{% for blog in blog_list %}
{{ blog.title }}

{ % endfor %}

 

 

{% if blog_list %}
게시물의 수 : {{ blog_list | length }}

{% else %}
게시물이 없습니다.

 

 

 

{% comment %}    {% endcomment %}

 

 

 

 

 

 

 

 

템플릿

# base.html

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>{% block title %}{% endblock%}</title>

</head>

<body>

    {% block content %}{% endblock %}

</body>

</html>

 

 

# extens 로 상속받는다.

# 아래 baseball 문장이 위 템플릿에 들어가게 된다.

# baseball.html

{% extends "base.html" %}

 

{% block title %}basketball{% endblock %}

 

{% block content %}

<!-- 농구기사들을 내용으로 넣으면 될 것입니다. -->

{% endblock %}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Model 과 Admin ( Admin 전용 BLOG 글 추가 )

# https://ssungkang.tistory.com/entry/Django-04-model-%EA%B3%BC-admin?category=320582

# DJango Administration UI 가 있음.

# 이 파트는 디비 연동하는 부분이 일반적이지 않아서 일단 스킵하고, 아래 사용자 전용 글 쓰기 파트 참조

 

 

# models.py

class Blog(modesl.Model):

    title = models.CharField(max_length = 200)
    pub_date = models.DateField('date published')

    body = models.TextField()

 

# settings.py

DATABASES = {

...

}

 

python manage.py makemigrations

 

python manage.py migrate

 

python manage.py createsuperuser

 

 

 

 

 

 

 

반응형

'Python, 파이썬' 카테고리의 다른 글

Django Rest FrameWork  (0) 2020.02.07
기본문법  (0) 2020.02.06
설치.DJango + Redis + Celery  (0) 2020.01.29
설치.Windows10.Request Module  (0) 2019.08.06
Reference  (0) 2018.12.03

설치.DJango + Redis + Celery

Python, 파이썬
반응형

참조 > https://whatisthenext.tistory.com/127

동기 vs 비동기

 

(이미치 출처 : http://ojava.tistory.com/17)

어떤 서비스에 회원가입을 하면 메일이 날라오는 경우가 있다.

  1. 동기 : 메일이 날라올 때까지 아무것도 하지 못한다.

  2. 비동기 : 메일이 날라오지 않더라도 다른 작업을 할 수 있다.

비동기 방식이 짱짱맨 아니냐 하겠지만 어떤 방식이건 간에 장단점이 존재한다. 아무튼, 회원가입 축하 이메일 발송은 사실 고객(client)에게 중요한 부분이 아니다. 일단 가입을 하고 서비스를 이용하기를 원할 것이다. 이러한 이메일 발송은 비동기 처리로 보낼 수 있다. 이를 백그라운드에 보낸다고 표현한다.

 

 

# Djnago + Celery + Redis

Celery는 일꾼이다. 해야 할 일들을 처리한다.
Reids는 주인이다. 메시지 브로커를 담당한다.

Celery란?

Celery는 안 보이는 곳에서 열심히 일하는 (백그라운드)일꾼이다. 처리해야 할 일을 Queue로 쌓아둔다.큐(queue)에 쌓인 일을 일꾼들이 가져다가 열심히 일을한다. 파이썬 언어로 작성되어 있다.

Redis란?

Redis는 실제 컴퓨터 메모리를 이용한 캐쉬다. Key와 Value값을 이용해 처리할 작업을 Celery에게 보낸 다음 캐쉬 시스템에서 해당 키를 없애는 방식으로 동작한다.

좋은 점은 로컬과 DB사이에서 자료가 왔다갔다 하는 것보다 메모리에서 캐쉬를 가져다 쓰는 것이 훨씬 빠르다는 것이다. 따라서 특정 데이터를 반복적으로 돌려줘야 한다면 메모리 캐쉬를 사용하면 좋다.

설치할 때 주의점

Celery는 파이썬 언어로 작성되어 있기 때문에 가상환경 위에서 pip를 이용해 설치한다.
Redis는 인 메모리를 이용한다고 했었다. 따라서 wget으로 설치한다.

 

 

1. 설치하기

1-1 Celery 설치하기

pip install 'celery[redis]'

pip를 이용해 cerlry 모듈과 redis와의 연동을 위한 dependency를 한 번에 설치한다. redis를 설치하지 않아도 일단 의존성 패키지는 설치 된다. 작은 따옴표('')를 꼭 붙여줘야 설치가 된다.

 

 

 

설치를 한뒤 pip list로 확인하면 amqp, billiard, celery, kombu, redis, vine 등이 함꼐 설치된다(나도 처음 알았다).

Celery는 수행할 작업(task) 및 실행을 의뢰받을 브로커(AMQP, Redis)를 정의한다.

1-2 Redis 설치하기

$ wget http://download.redis.io/redis-stable.tar.gz

$ tar xvzf redis-stable.tar.gz

cd redis-stable

$ make

$ redis-server # redis 실행

$ redis-cli ping # 정상 설치되었는지 확인

> PONG

PONG 메시지를 띄우면 설치 성공이다.

 

 

 

2. Django와 연동하기

디렉토리 구조

 

 

프로젝트 루트 폴더(project root folder) : celery (장고 프로젝트를 담는 최상위 폴더)
프로젝트 폴더(project folder) : django_app (여러 앱들로 구성되는 장고 프로젝트 폴더)
프로젝트 환경설정 폴더(project settings folder) : config


[프로젝트 폴더] / [환경설정 폴더] / __init__.py

from .tasks import app as celery_app

 

__all__ = ['celery_app']

[프로젝트 폴더] / [환경설정 폴더] / settings.py

BROKER_URL = 'redis://localhost:6379/0'

CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'

[프로젝트 폴더] / [환경설정 폴더] / tasks.py(파일 추가)

import os

from celery import Celery

 

# `celery` 프로그램을 작동시키기 위한 기본 장고 세팅 값을 정한다. 

os.environ.setdefault('DJANGO_SETTINGS_MODULE''config.settings')

 

app = Celery('config')

 

# namespace='CELERY'는 모든 셀러리 관련 구성 키를 의미한다. 반드시 CELERY라는 접두사로 시작해야 한다. 

app.config_from_object('django.conf:settings'namespace='CELERY')

 

# 장고 app config에 등록된 모든 taks 모듈을 불러온다. 

app.autodiscover_tasks()

 

@app.task

def add(x, y):

    return x + y

3. Celery + Redis 실행시켜보기

실행하기
주의점 : 프로젝트 폴더에 진입한 뒤! 쉘에서 다음 명령을 입력해야 한다.

celery -A   [파일이름]   worker --loglevel=info

cerlry -A    config    worker --loglevel=info

실행 결과

(django_ev) ➜  django_app celery -A config worker --loglevel=info

 

 -------------- celery@chulgyoo-15ZD960-GX30K v4.0.2 (latentcall)

---- **** -----

--- * ***  * -- Linux-4.8.0-58-generic-x86_64-with-debian-stretch-sid 2017-07-15 05:53:49

-- * - **** ---

** ---------- [config]

** ---------- .> app:         config:0x7f5380456358

** ---------- .> transport:   redis://localhost:6379//

** ---------- .> results:     redis://localhost:6379/

*** --- * --- .> concurrency: 4 (prefork)

-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)

--- ***** -----

 -------------- [queues]

                .> celery           exchange=celery(direct) key=celery

 

[tasks]

  . config.tasks.add # [tasks]를 통해서 비동기로 작업 할 수 있는 목록들이 나온다. 현재는 add 하나.

 

[2017-07-15 05:53:50,139: INFO/MainProcess] Connected to redis://localhost:6379//

[2017-07-15 05:53:50,149: INFO/MainProcess] mingle: searching for neighbors

[2017-07-15 05:53:51,172: INFO/MainProcess] mingle: all alone

[2017-07-15 05:53:51,214: WARNING/MainProcess] /home/chulgyoo/.pyenv/versions/3.6.1/envs/django_ev/lib/python3.6/site-packages/celery/fixups/django.py:202: UserWarning: Using settings.DEBUG leads to a memory leak, never use this setting in production environments!

  warnings.warn('Using settings.DEBUG leads to a memory leak, never')

[2017-07-15 05:53:51,215: INFO/MainProcess] celery@chulgyoo-15ZD960-GX30K ready.

Debug(로컬)에서 실행하면 메모리

오류가 발생한다면

  1. Cannot connet 문제

    BROKER_URL 또는 RESULT_BACKEND를 잘못 지정해줬을 가능성이 있다.

  2. No moule named '[모듈이름]'

    • 모듈 이름을 잘못 임포트 했다. 프로젝트 폴더 안에서 명령어를 실행한게 맞는지, 내가 만든 파일 이름이 맞는지 확인해야 한다.

 

4. Celery를 이용한 작업처리하기

작업을 실행시켜보자

 

 

Celery를 실행시킨 상태에서 터미널을 하나 더 켠 뒤, 작업을 진행해보자. 위와 같이 있으면 된다.

python shell

 

>>> from config.tasks import add

>>> result = add.delay(44)

>>> result = add.delay(44)

>>> result = add.delay(44)

>>> result = add.delay(44)

>>> result = add.delay(44)

5번을 실행시킨 뒤, Celery Shell을 확인해보면 Received task라는 메시지와 함께 작업시간을 확인할 수 있다. 간단한 계산이기 때문에 많은 시간이 걸리지 않는다.

 

 

5. Celery WorkFlow

  1. @app.task로 처리하고 싶은 일에 딱지를 붙인다.

  2. add 작업에 delay를 붙이면 Redis Backend에 기록이 저장된다.

  3. Redis는 Celery에게 일을 준다.

  4. 일을 받은 Celery는 add 작업을 시작한다.

Redis

Redis는 아무래도 In-memory를 사용하는 것이 포인트다.
Celery는 파이썬 언어로 건드려볼 수 있지만, Redis는 간단한 편(?)이다.

설치

$ wget http://download.redis.io/redis-stable.tar.gz

$ tar xvzf redis-stable.tar.gz

cd redis-stable

$ make

서버 시작

$ redis-server

서버 확인

$ redis-cli

 

127.0.0.1:6379 > ping

PONG

get, set 명령어 실행
서두에서 key와 value값으로 작업을 Celery에게 보낸다고 언급했었다.

127.0.0.1:6379 > set mykey "myvalue"

OK

127.0.0.1:6379 > get mykey

"myvalue"

서버 정지

$ redis-cli shutdown

참고한 글

  1. Redis 설치하기
    http://www.tutorialbook.co.kr/entry/Ubuntu-Redis-%EC%B5%9C%EC%8B%A0-stable-%EB%B2%84%EC%A0%84-%EC%84%A4%EC%B9%98%ED%95%98%EA%B8%B0

  2. Celery + Redis
    http://dgkim5360.tistory.com/entry/python-celery-asynchronous-system-with-redis

    • Celery + Redis 연동에 관한 전반적인 정보를 얻었습니다.

 

반응형

'Python, 파이썬' 카테고리의 다른 글

기본문법  (0) 2020.02.06
DJango (Windows)  (0) 2020.01.31
설치.Windows10.Request Module  (0) 2019.08.06
Reference  (0) 2018.12.03
Manage Excel  (0) 2018.12.03

설치.Windows10.Request Module

Python, 파이썬
반응형

1) cmd 를 관리자모드로 실행

 

2) Python 디렉토리 아래 Scripts 로 이동

cd C:\Users\myLocalUserName\AppData\Local\Programs\Python\Python36\Scripts

 

3) pip install requests

반응형

'Python, 파이썬' 카테고리의 다른 글

DJango (Windows)  (0) 2020.01.31
설치.DJango + Redis + Celery  (0) 2020.01.29
Reference  (0) 2018.12.03
Manage Excel  (0) 2018.12.03
파이썬 설치시  (0) 2018.06.09

Reference

Python, 파이썬
반응형

http://pyqt.sourceforge.net/Docs/PyQt5/


https://opentutorials.org/module/544/4998

반응형

'Python, 파이썬' 카테고리의 다른 글

설치.DJango + Redis + Celery  (0) 2020.01.29
설치.Windows10.Request Module  (0) 2019.08.06
Manage Excel  (0) 2018.12.03
파이썬 설치시  (0) 2018.06.09
Python 3.6.5 Release  (0) 2018.06.09

설치

Python, 파이썬/GUI 프로그래밍
반응형

2018-650

[ 참조 ] https://www.youtube.com/watch?v=YUdlGBAPNrU&t=1350s


0) Python 3.5.2 로 설치.


1) wxPython, PyQt, TkInter 필요


pip install PyQt5

pip install pyqt5-tools # Python 3.6 혹은 3.7 에서 미지원할 수도 있음.


pip install pyinstaller

> pyinstall main.py


설치 추가 참조 : https://opentutorials.org/module/544/5000


2) PyQT 를 이용하는 방법 두가지

2.1) Qt Designer 사용

2.1.1) 방식1. 생성된 XML 기반의 ui => pyuic5 로 python 파일로 변환

- 디자인 변경시 마다 변환이 귀찮다.


2.1.2) 방식2. 생성된 XML 기반의 ui => loadUi() 메서드 사용

- 변환 없이 바로 사용가능

class Form (QtWidgets QDialog):

  def __init__(self, parent=None):

    QtWidgets.QDialog.__init__(self, parent)


    self.ui = uic.loadui("ui,ui", self)

    self.pb = QtWidgets.QPushButton("test')

    self.pb.show()

   

- 코드로 직접 디자인


3) QWidget

3.1) QWidget 은 가장 기본 위젯

- 즉 모든 위젯은 QWidget 을 피상속 ( 윈도프레임/타이틀, 입력이벤트및 출력처리, 위치/크기등 속성)

- Ex>



QPushButton : 눌리는 버튼모양

QAbstractButton : 클릭 가능해.

QWidget : 기본 위젯


3.2) 시그널과 슬롯

위젯 프로토콜은,

- 모든 위젯은 시그널과 슬롯이 있다.

- 시그널은 정의된 기능이 실행되면 결과 값을 보낸다. (실행할 수 있는 함수가 아니다.)

- 슬롯은 시그널이 보낸값을 받아서 설정된 행위를 한다. (슬롯은 시그널과 연결시켜야 상호간의 통신 가능하다.)


3.3) 사용자 커스텀 위젯

방법1) QWidget 상속

방법2) 다른 Widget 확장


아래 그림)

 - 이미 있는 Widget 상속후 기능추가 변경 =>새로운 시그널 및 슬롯 작성

- 여러 위젯 합쳐서 하나의 위젯으로 만들기



4. 예제)

- 창생성 참조

https://github.com/RavenKyu/OpenTutorials_PyQt/commit/b32b434637e7020b3648205a306dc88881c11cde


- 메뉴바 추가

https://github.com/RavenKyu/OpenTutorials_PyQt/commit/ddb11952dcb00645077e6aa2fc3eb67c96a1ce5a


-국제화 한국어 추가 ( 시스템 로케일 따라 국어 변경 )

https://github.com/RavenKyu/OpenTutorials_PyQt/commit/79aca341cfe995af3c9e728dc0a5e57677cd7956

: 언어 지원이 필요한 문자열에 tr() 함수 사용

: pro 파일제작하여, tr() 이 포함된 파이썬 파일명. 생성할 언어파일명

: pylupdate5 -noobsolete notepad_i18n.pro - 명시된 파일에서 tr() 이 있는 부분을 검사. 국가별 ts 파일 생성

: lrelease.exe "translate\ko_KR.ts" qm파일로 변환

: lrelease.exe는 Qt5 를 설치 또는 pip install PyQt_tools 설치


- 국제화 예제 (언어를 자동 및 수동으로 설정)

https://github.com/RavenKyu/OpenTutorials_PyQt/commit/29617f50b8dfa83b8d4aee35221cc28f5f02c3bc


- 텍스트 에디터 추가 (QTextEdit, 확장성을 위해 사용자 커스텀 위젯화)

https://github.com/RavenKyu/OpenTutorials_PyQt/commit/204815dec080b20d1b82e6c6f040e4b3ed9eca36


- 메뉴 활성화 (새로만들기, 열기, 저장)

https://github.com/RavenKyu/OpenTutorials_PyQt/commit/a36866caac5d1dfdf6b6e5628a7087169ff8feb6


- 상태표시바

https://github.com/RavenKyu/OpenTutorials_PyQt/commit/4c3b3f0d0e60024403d4596f99d477666832ec81



- 프린터 추가

https://github.com/RavenKyu/OpenTutorials_PyQt/commit/ffdba77d5ad044dfc07072d075bb1fbd1e07753b






반응형

Manage Excel

Python, 파이썬
반응형

2018-653


API 참조)

- automatetheboringstuff.com

- openpyxl.readthedocs.io/end/default


1) pip install openpyxl


2)

Python IDLE Shell> import openpyxl

Python IDLE Shell> openpyxl.__version__


3) 

import os

os.chdir('c:\\users\pc1\\desktop')

wb = openpyxl.load_workbook('example.xlsx') // 미리 example.xlsx 를 만들어 둘것. 내용은 아무거나.

type(wb)

wb.get_sheet_names()

sheet = wb.get_sheet_by_name('Sheet1')

type(sheet)

sheet['A1'].value='abcd'

wb.save(example2.xlsx')


sheet.title = "My Sheet"

sheet.cell(row=1, column=3).value


for i in range(2, 5) : print(sheet.cell(row=i, column=3).value)


sheet.max_row

sheet.max_column


openpyxl.cell.get_column_letter(1) // 'A'

openpyxl.cell.column_index_from_string('Z') // 26


wb.create_sheet(title='My Sheet Name', index=1)

wb.save('example4.xlsx')


sheet.row_dimensions[1].height

sheet.row_dimensions[1].height = 70

sheet.column_dimensions['B'].width = 20


from openpyxl.styles import Font

sheet['B1'].font = Font(sz=14, bold=True, italic=True)


import random

for i in range(1, 11) : sheet ['A' + str(i)].value = random.randint(1, 100)


sheet['c8'].value = '=SUM(C1:C7)'


// http://pyautogui.readthedocs.io/en/latest/

// https://pyautogui.readthedocs.io/en/latest/install.html

// pip install pyautogui

import pyautogui

pyautogui.click(100, 100)


반응형

'Python, 파이썬' 카테고리의 다른 글

설치.DJango + Redis + Celery  (0) 2020.01.29
설치.Windows10.Request Module  (0) 2019.08.06
Reference  (0) 2018.12.03
파이썬 설치시  (0) 2018.06.09
Python 3.6.5 Release  (0) 2018.06.09

파이썬 설치시

Python, 파이썬
반응형

1) 설치시 PATH 를 체크후에 설치한다.

tensorflow 를 할거라면 64bit 를 설치한다.


2) 설치후에 다시 설치 시도 => Modify => StandAlone, Debug 도 추가 설치 가능하다.


3) 설치후에 버전 확인 가능.

python -V

python3 --version Python 3.6.5

반응형

'Python, 파이썬' 카테고리의 다른 글

설치.DJango + Redis + Celery  (0) 2020.01.29
설치.Windows10.Request Module  (0) 2019.08.06
Reference  (0) 2018.12.03
Manage Excel  (0) 2018.12.03
Python 3.6.5 Release  (0) 2018.06.09

Python 3.6.5 Release

Python, 파이썬
반응형

https://www.python.org/downloads/release/python-365/

반응형

'Python, 파이썬' 카테고리의 다른 글

설치.DJango + Redis + Celery  (0) 2020.01.29
설치.Windows10.Request Module  (0) 2019.08.06
Reference  (0) 2018.12.03
Manage Excel  (0) 2018.12.03
파이썬 설치시  (0) 2018.06.09