StoryCode

'전체 글'에 해당되는 글 570건

  1. Javascript.Hoisting
  2. Django Rest FrameWork
  3. 기본문법

Javascript.Hoisting

IT 용어, 인터넷 활용 등등
반응형

"var 변수;" 와 "function 함수명" 으로 선언된 경우, 최상위에 미리 자동 선언된다.

고로, 함수내부에서 어디서든 불러 사용할 수 있다.

 

"let 변수" 와 "함수명 = function" 은 할당 혹은 정의 이전에 사용할 수 없다.

 

참조) https://gmlwjd9405.github.io/2019/04/22/javascript-hoisting.html

반응형

'IT 용어, 인터넷 활용 등등' 카테고리의 다른 글

CI, DI  (0) 2020.04.20
ab (apache bench) 테스트  (0) 2020.03.26
whois.com 에서 whois.co.kr 로 이전하기  (0) 2019.07.01
Serverless Architecture  (0) 2018.12.06
Manage, Unmanaged, Native, JIT  (0) 2018.12.02

Django Rest FrameWork

Python, 파이썬
반응형

# 참조 ) https://ssungkang.tistory.com/entry/Django-django-rest-framework-%EB%A5%BC-%EC%9C%84%ED%95%9C-JSON-%EA%B8%B0%EC%B4%88?category=366160

 

   
JSON 처리 import json

myData = {
  "squadName": "Super hero squad",
  "homeTown": "Metro City",
  "formed": 2016,
  "secretBase": "Super tower",
  "active": True,
  "members": [
    {
      "name": "Molecule Man",
      "age": 29,
      "secretIdentity": "Dan Jukes",
      "powers": [
        "Radiation resistance",
        "Turning tiny",
        "Radiation blast"
      ]
    }
  ]
}

print(type(myData)) # <class 'dict'>

myDataJson = json.dumps(myData)
print(type(myDataJson)) # <class 'str'>

myDataReturn = json.loads(myDataJson)
print(type(myDataReturn)) # <class 'dict'>
ModelSerializer 를 통한 JSON 직렬화 설명 1) ModelSerializer 를 통해  JSONRenderer 에서 변환가능한 형태로 먼저 데이터를 변환
참조1) JSON 을 생성하는 Serializer 는 html 을 생성하는 Django.Form 과 유사
참조2) Serializer 는 Django.Form 과 유사, ModelSerializer = DJango.ModelForm 과 유사


ModelSerializer 를 통한 JSON 직렬화 예제 참조) https://ssungkang.tistory.com/entry/Django-django-rest-framework-%EB%A5%BC-%EC%9C%84%ED%95%9C-JSON-%EC%A7%81%EB%A0%AC%ED%99%94?category=320582



models.py
from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=100)
    message = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    update_at = models.DateTimeField(auto_now=True)







serializers.py
from rest_framework import serializers
from .models import Post

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = '__all__'







# config/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('core/', include('core.urls'), name='core'),
]






# core/urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from . import views

router = DefaultRouter()
router.register(r'posts', views.PostViewSet)

urlpatterns = [
    path('', include(router.urls)),
]







views.py
from django.shortcuts import render
from rest_framework import viewsets
from .models import Post
from .serializers import PostSerializer

class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer






serializer = PostSerializer(post)
serializer.data

# {'id': 2, 'title': '제목 내용', 'message': '메세지 내용', 'created_at': '2019-11-18T18:52:57.489893Z', 'update_at': '2019-11-18T19:22:53.717588Z'}
type(serializer.data) 
# <class 'rest_framework.utils.serializer_helpers.ReturnDict'




serializer = PostSerializer(Post.objects.all())
serializer.data
# 오류

serializer = PostSerializer(Post.objects.all(), many=True)
serializer.data
# [OrderedDict([('id', 2), ('title', '제목 내용'), ('message', '메세지 내용'), ('created_at', '2019-11-18T18:52:57.489893Z'), ('update_at', '2019-11-18T19:22:53.717588Z')]), OrderedDict([('id', 3), ('title', '임시제목'), ('message', 'ㅡㅏㅏ'), ('created_at', '2019-11-18T18:52:57.489893Z'), ('update_at', '2019-11-18T18:52:57.499208Z')])]
type(serializer.data) 
<class 'rest_framework.utils.serializer_helpers.ReturnList'>





뷰에서의 JSON 응답 )
from django.core.serializers.json import DjangoJSONEncoder
from django.db.models.query import QuerySet

# QuerySet 타입에 대해서는 tuple로 변환
# Post 타입에 대해서는 dict로 변환
# 그 외에는 DjangoJSONEncoder 로 변환
class MyJSONEncoder(DjangoJSONEncoder):
    def default(self, obj):
        if isinstance(obj, QuerySet):
            return tuple(obj)
        elif isinstance(obj, Post):
            return {'id':obj.id, 'title': obj.title, 'message': obj.message }
        return super().default(obj)




# View 에서 json 리턴
from django.http import JsonResponse

data = Post.objects.all() # 직렬화할 QuerySet
encoder = MyJSONEncoder # DjangoJSONEncoder를 커스튬한 Encoder
safe = False # default = True 로서 변환할 데이터의 타입이 dict인지 확인합니다. dict 가 아닐 경우에는 False로 설정해주어야 합니다. QuerySet 은 dict 타입이 아니므로 False로 설정합니다.
json_dumps_params = {'ensure_ascii':False} # 한글 등의 유니코드는 16진수로 표현되므로 이를 False 로 바꿔주면 한글문자가 그대로 출력됩니다.
kwargs = {}

response = JsonResponse(data, encoder, safe, json_dumps_params, **kwargs)

response

response.content.decode('utf8')
# [{"id": 2, "title": "제목 내용", "message": "메세지 내용"}, {"id": 3, "title": "임시제목", "message": "ㅡㅏㅏ"}]

 

반응형

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

DJango 의 장점  (0) 2020.02.12
DJango.ORM  (0) 2020.02.12
기본문법  (0) 2020.02.06
DJango (Windows)  (0) 2020.01.31
설치.DJango + Redis + Celery  (0) 2020.01.29

기본문법

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