2016/04/05

[Python] urllib2 Library MultiPartForm class

로컬에서 MultiPartForm 전송


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/


[Python] 한글 처리중 에러 (UnicodeEncodeError: 'ascii' codec can't encode characters in position ....)

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)



문서 상단에 선언시 해결 가능

import sys
reload(sys)
sys.setdefaultencoding('utf-8')


사용하면 위험하다는 의견과 무방하다는 의견이 분분하긴 한데 테스트 결과 문제는 없었다.



참고 :
http://stackoverflow.com/questions/3828723/why-should-we-not-use-sys-setdefaultencodingutf-8-in-a-py-script




[Python] utf-8 선언

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


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






2016/01/20

[ffmpeg] ubuntu ffmpeg install (E: Package 'ffmpeg' has no installation candidate)

aws ubuntu 에 ffmpeg 설치가 필요했다.

ubuntu 버전은 14.04


1. 컴파일 설치
 
https://trac.ffmpeg.org/wiki/CompilationGuide/Ubuntu 참조


2. apt-get 설치

https://www.ffmpeg.org/download.html 에서 링크를 타고


https://launchpad.net/~mc3man/+archive/ubuntu/trusty-media 로 이동해보니 방법이 쭉 나와있다

sudo add-apt-repository ppa:mc3man/trusty-media
sudo apt-get update
sudo apt-get dist-upgrade
sudo apt-get install ffmpeg

순서대로 진행하면 완료~



- ubuntu ffmpeg install
- apt-get install ffmpeg
- E: Package 'ffmpeg' has no installation candidate

2016/01/19

Switching easily between Java JDKs on Mac OS X

original URL :
https://wimdeblauwe.wordpress.com/2014/03/20/switching-easily-between-java-jdks-on-mac-os-x/





I just came upon a neat little trick to easily switch what JDK you are using on the command line on Mac OS X (10.9.2 is the version I am using), courtesy of this AskDifferent answer.
First, add the following aliases in ~/.profile file:
alias setJdk6='export JAVA_HOME=$(/usr/libexec/java_home -v 1.6)'
alias setJdk7='export JAVA_HOME=$(/usr/libexec/java_home -v 1.7)'
alias setJdk8='export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)'
Open a new terminal window or use source ~/.profile to load the aliases.
Now you can easily switch between the installed JDKs:
> setJdk6
We can verify that Maven picks this up correctly:
> mvn --version
Apache Maven 3.0.4 (r1232337; 2012-01-17 09:44:56+0100)
Maven home: /Applications/maven/apache-maven-3.0.4
Java version: 1.6.0_65, vendor: Apple Inc.
Java home: /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
Default locale: en_US, platform encoding: MacRoman
OS name: "mac os x", version: "10.9.2", arch: "x86_64", family: "mac"
To go to JDK 7:
> setJdk7
And Maven shows:
> mvn --version
Apache Maven 3.0.4 (r1232337; 2012-01-17 09:44:56+0100)
Maven home: /Applications/maven/apache-maven-3.0.4
Java version: 1.7.0_45, vendor: Oracle Corporation
Java home: /Library/Java/JavaVirtualMachines/jdk1.7.0_45.jdk/Contents/Home/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "mac os x", version: "10.9.2", arch: "x86_64", family: "mac"
This works just as well to switch to the just released JDK 8:
> setJdk8
Maven output:
> mvn --version
Apache Maven 3.0.4 (r1232337; 2012-01-17 09:44:56+0100)
Maven home: /Applications/maven/apache-maven-3.0.4
Java version: 1.8.0, vendor: Oracle Corporation
Java home: /Library/Java/JavaVirtualMachines/jdk1.8.0.jdk/Contents/Home/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "mac os x", version: "10.9.2", arch: "x86_64", family: "mac"
Voila, simpel and effective!


2016/01/14

[ubuntu] ubuntu jdk 1.7 install

- ubuntu jdk 1.7 install
- ubuntu jdk install
- ubuntu jdk 설치



OpenJDK

sudo apt-get install openjdk-7-jdk



Oracle JDK

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer
sudo apt-get install oracle-java7-set-default


http://hangaebal.tistory.com/12

[ubuntu] ubuntu tomcat 7 install


- ubuntu tomcat install
- ubuntu tomcat7 install



sudo apt-get install tomcat7




http://hangaebal.tistory.com/11



[IntelliJ] IntelliJ 14 download

- IntelliJ 14 download, install
- IntelliJ Previous version download
- IntelliJ 14 다운로드, 설치
- IntelliJ 이전 버전 다운로드, 설치


JetBrains 이전 버전 다운로드 링크 페이지
https://confluence.jetbrains.com/display/IntelliJIDEA/Previous+IntelliJ+IDEA+Releases


혹은 다운로드 페이지에서 Previous versions 링크 클릭 해도 해당 페이지로 이동 가능



http://hangaebal.tistory.com/10




[JDK 1.7] JDK 1.7 설치, JDK 1.7 install

-----------------------
- jdk 1.7 install
- jdk 1.7 install on mac
-----------------------

1. 다운로드 페이지 이동
http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html

2. Java SE Development Kit 다운로드 목록에서 Accept License Agreement 클릭해서 약관 동의

3. OS에 맞는 항목 다운로드 후 설치
- Mac은 Mac OS X x64
- Windows의 경우 32비트는 Windows x86 / 64비트는 Windows x64



http://hangaebal.tistory.com/9

[Maven] Maven Install on Mac OS X, Mac OS에 Maven 설치

------------------------------------------
- mvn: command not found
- mvn install on mac
- maven install on mac
- maven install on osx
- maven mac 설치
------------------------------------------



Mac 환경에서 Maven을 설치하려고 보니 dmg나 pkg 같은 설치 형태로는 제공하고 있지 않다.
(http://maven.apache.org/download.cgi)

직접 받아서 설치해도 되지만 brew를 설치했다면 터미널에서 명령어 하나로 간단히 설치 가능하다.
(brew 설치는 http://hangaebal.tistory.com/7 참고)

brew install maven


메이븐 설치 끝!


http://hangaebal.tistory.com/8