# serverless.yml

service: service-name
provider:
  name: aws
  environment:
    FOO: bar

functions:
  hello:
    handler: handler.hello
    FOO2: bar2

 

# Python handler

 

import os
...

FOO = os.environ['FOO'])
...

 

 

참고 :

https://serverless.com/framework/docs/providers/aws/guide/functions#environment-variables

pyenv 로 Python 버전 및 개발 환경 관리

설치

  • OS X
    $ brew update
    $ brew install pyenv
    $ brew install pyenv-virtualenv
    
  • 기타 OS
    1. installer 활용 설치
      $ curl -L https://raw.githubusercontent.com/yyuu/pyenv-installer/master/bin/pyenv-installer | bash
      
    2. PATH 설정
      • ~/.bash_profile 에 다음 내용 추가
      export PATH="~/.pyenv/bin:$PATH"
      eval "$(pyenv init -)"
      eval "$(pyenv virtualenv-init -)"
      
      • 적용
      $ source ~/.bash_profile
      

사용

  1. pyenv로 Python 설치
    • 설치 가능 버전 확인
    $ pyenv install --list
    
    • 설치는 `pyenv install 3.5.2' 형태로 가능
  2. pyenv-virtualenv 로 가상 환경 관리
    https://github.com/yyuu/pyenv-virtualenv pyenv-installer 에 포함이 되어있기 때문에 추가로 설치할 것은 없다.
    1. 가상 환경 생성
      $ pyenv virtualenv 3.5.2 v352
      
      • pyenv virtualenv 버전 환경명 형태로 사용
      • 버전을 지정하지 않으면 현재 지정된 버전으로 적용됨
    2. 가상 환경 활성화
      $ pyenv activate v352
      
      • pyenv activate 환경명 형태로 사용
      • pyenv deactivate 로 비활성화


Django Tutorial


설치

  1. python 설치
  2. Django 설치
    • pip install Django
    • 설치 확인은 python -m django --version

프로젝트 생성

  1. 커맨드로 기본 프로젝트 구조 생성
    • django-admin startproject mysite
  2. 생성 파일 확인
    mysite/
        manage.py
        mysite/
            __init__.py
            settings.py
            urls.py
            wsgi.py
    
    • 바깥쪽 mysite/ 폴더는 프로젝트를 감싸는 역할을 하고, 이름은 Django 에게 중요하지 않아서 원하면 바꿔도 된다.
    • manage.py : Django 프로젝트와 상호작용 할 수 있도록 해주는 커맨드라인 유틸리티이다. 더 상세한 내용은 django-admin and manage.py 에서 확인할 수 있다.
    • 안쪽 mysite/ 폴더는 프로젝트를 위한 실제 Python 패키지이다. 이 폴더명은 Python 패키지 이름이 되며 안에 있는 것을 import 하려면 이 이름을 사용해야 한다. (예: mysite.urls).
    • mysite/__init__.py : Python에게 이 디렉토리가 Python 패키지라고 간주하도록 하는 빈 파일이다. Python 초심자라면 공식 Python 문서인 more about packages를 읽어라.
    • mysite/settings.py 이 Django 프로젝트의 설정이다. Django settings에서 설정하는 방법에 대해 알려준다.
    • mysite/urls.py : 이 Django 프로젝트의 URL 선언이다; Django로 생성된 사이트의 목차이다. (URL dispatcher)[https://docs.djangoproject.com/en/1.9/topics/http/urls/]에서 URL에 대해 더 읽을 수 있다.
    • mysite/wsgi : 프로젝트를 WSGI 호환 웹 서버로 제공하기 위한 엔트리 포인트이다. (How to deploy with WSGI)[https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/]에서 WSGI과 함께 배포하는 방법에 대한 자세한 내용을 참조할 수 있다.

개발 서버 실행

  1. 실행
    • 바깥쪽 mysite 폴더로 이동한 뒤 커맨드를 이용해 실행한다. python manage.py runserver
    • 실행시 나오는 데이터베이스 관련 경고는 곧 다룰 것이므로 지금은 무시한다.
    • Django 에 경량 웹서버를 포함해두어서 배포 전 까지 Apache 등의 서버 설정을 고려하지 않고 빠르게 개발할 수 있다.
    • 개발 서버는 실제 환경에서 사용하지 말고 개발 중에만 사용하도록 한다.
  2. 접속 확인

Excel Data read




라이브러리 설치

0. pip가 설치되어있지 않다면 먼저 설치

$ sudo easy_install pip


1. pip를 이용해서 openpyxl 라이브러리 설치

$ sudo pip install openpyxl




2. 기본 활용

>>> from openpyxl import load_workbook
>>> wb = load_workbook(filename = 'empty_book.xlsx')
>>> sheet_ranges = wb['range names']
>>> print(sheet_ranges['D18'].value)
3











로컬에서 MultiPartForm 전송시 유용한 class


import itertools
import mimetools
import mimetypes
from cStringIO import StringIO
import urllib
import urllib2

class MultiPartForm(object):
    """Accumulate the data to be used when posting a form."""

    def __init__(self):
        self.form_fields = []
        self.files = []
        self.boundary = mimetools.choose_boundary()
        return
    
    def get_content_type(self):
        return 'multipart/form-data; boundary=%s' % self.boundary

    def add_field(self, name, value):
        """Add a simple field to the form data."""
        self.form_fields.append((name, value))
        return

    def add_file(self, fieldname, filename, fileHandle, mimetype=None):
        """Add a file to be uploaded."""
        body = fileHandle.read()
        if mimetype is None:
            mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
        self.files.append((fieldname, filename, mimetype, body))
        return
    
    def __str__(self):
        """Return a string representing the form data, including attached files."""
        # Build a list of lists, each containing "lines" of the
        # request.  Each part is separated by a boundary string.
        # Once the list is built, return a string where each
        # line is separated by '\r\n'.  
        parts = []
        part_boundary = '--' + self.boundary
        
        # Add the form fields
        parts.extend(
            [ part_boundary,
              'Content-Disposition: form-data; name="%s"' % name,
              '',
              value,
            ]
            for name, value in self.form_fields
            )
        
        # Add the files to upload
        parts.extend(
            [ part_boundary,
              'Content-Disposition: file; name="%s"; filename="%s"' % \
                 (field_name, filename),
              'Content-Type: %s' % content_type,
              '',
              body,
            ]
            for field_name, filename, content_type, body in self.files
            )
        
        # Flatten the list and add closing boundary marker,
        # then return CR+LF separated data
        flattened = list(itertools.chain(*parts))
        flattened.append('--' + self.boundary + '--')
        flattened.append('')
        return '\r\n'.join(flattened)

if __name__ == '__main__':
    # Create the form with simple fields
    form = MultiPartForm()
    form.add_field('firstname', 'Doug')
    form.add_field('lastname', 'Hellmann')
    
    # Add a fake file
    form.add_file('biography', 'bio.txt', 
                  fileHandle=StringIO('Python developer and blogger.'))

    # Build the request
    request = urllib2.Request('http://localhost:8080/')
    request.add_header('User-agent', 'PyMOTW (http://www.doughellmann.com/PyMOTW/)')
    body = str(form)
    request.add_header('Content-type', form.get_content_type())
    request.add_header('Content-length', len(body))
    request.add_data(body)

    print
    print 'OUTGOING DATA:'
    print request.get_data()

    print
    print 'SERVER RESPONSE:'
    print urllib2.urlopen(request).read()


참고:
https://pymotw.com/2/urllib2/


SyntaxError: Non-ASCII character ......  but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details



최상단에 해당 문서의 인코딩을 선언하면 된다.
# -*- coding: utf-8 -*-



+ Recent posts