Ref

Installing Python packages (Offline mode) - IBM Documentation

Download packages from pip

$ pip download -d path/to/dir PACKAGE_NAME=VERSION

Create requirements

$ vi pre_req.txt
numpy=-1.2.1
keras=2.0.2

Install local packages from pip

$ pip install --no-deps --no-index --find-links=/path/to/dir -r pre_req.txt

Remove local installed pacakges

$ pip uninstall -r pre_req.txt

'Python' 카테고리의 다른 글

pipsi - pip script installer  (1) 2019.06.04
SSH with python3  (0) 2019.01.25
flask: download file from directory  (0) 2019.01.02
Flask on apache via mod_wsgi  (0) 2018.12.06
Python 2.6 to 2.7 (or 3.x)  (0) 2018.11.23

When you install pipsi from get-pipsi.py, You should not execute python with sudo.

Just export PATH for pipsi

'Python' 카테고리의 다른 글

Python pip local package install  (0) 2023.06.21
SSH with python3  (0) 2019.01.25
flask: download file from directory  (0) 2019.01.02
Flask on apache via mod_wsgi  (0) 2018.12.06
Python 2.6 to 2.7 (or 3.x)  (0) 2018.11.23

paramiko 모듈을 이용하여 원격 리눅스 서버에 SSH 접속


pip를 이용하여 paramiko 모듈 설치


1
python -m pip install paramiko
cs


paramiko ssh 기본 접속 설정


1
2
3
4
5
6
7
8
9
10
11
import paramiko
import time
 
def main():
    HOST = 'ip_address'
 
    try:
        ssh = paramiko.SSHClient()
        # SSH Host key 설정
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(HOST, username='USERNAME', password='PW')
cs


기본적으로 한번 connect 된 상태에서 명령어를 실행할 때 마다 하나의 채널이 생성되고 종료되는 것이 반복된다.

su 커맨드를 사용하기 위해서는 채널을 유지시켜 줘야 하는데, 이 때 invoke_shell()를 사용하면 된다.


1
2
3
4
channel = ssh.invoke_shell()
 
channel.send('su -\n')
channel.send('password\n')
cs



전체 코드


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import paramiko
import time
 
def main():
    HOST = 'ip_address'
 
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(HOST, username='USERNAME', password='PW')
        channel = ssh.invoke_shell()
 
        channel.send('su -\n')
        outdata, errdata = waitStreams(channel)
        print (outdata)
        channel.send('PW2\n')
        outdata, errdata = waitStreams(channel)
        print (outdata)
 
        channel.send('touch python_test_is_complete\n')
        outdata, errdata = waitStreams(channel)
        print (outdata)
 
    finally:
        if ssh is not None:
            ssh.close()
 
# python 모듈을 실행하는 커맨드 라인에서 출력 결과를 보여는 
def waitStreams(chan):
    time.sleep(1)
    outdata=errdata = ""
 
    while chan.recv_ready():
        outdata += str(chan.recv(1000))
    while chan.recv_stderr_ready():
        errdata += str(chan.recv_stderr(1000))
 
    return outdata, errdata
 
if __name__ == "__main__":
    main()
cs



Python 3.7.2 Traceback


1
TypeError: can only concatenate str (not "bytes") to str
cs


전체코드 33 ~ 36: byte로 읽은 데이터를 str 타입으로 변환 시켜 저장해야 정상적으로 print를 사용할 수 있다.

'Python' 카테고리의 다른 글

Python pip local package install  (0) 2023.06.21
pipsi - pip script installer  (1) 2019.06.04
flask: download file from directory  (0) 2019.01.02
Flask on apache via mod_wsgi  (0) 2018.12.06
Python 2.6 to 2.7 (or 3.x)  (0) 2018.11.23

플라스크 앱 디렉토리에 일반 아파치 웹 서버 처럼 DocumentRoot 경로에 파일을 업로드하고 요청을 시도하면 404 또는 500 에러를 응답 받는다.




flask 앱에서는 send_from_directory 모듈을 사용하여 일반 아파치 서버 처럼 파일을 업로드하고 다운로드 받을 수 있다.


1
2
3
4
5
6
7
from flask import send_from_directory
 
...
 
 @app.route('/file/<path:filename>', methods=['GET', 'POST'])
 def download(filename):
     return send_from_directory(directory='file', filename=filename)
cs


file 이라는 서브 디렉토리 생성 후, 해당 위치에 파일을 업로드하고, flask 앱 라우팅을 통해 해당 경로에서 파일을 다운로드 받을 수 있도록 설정하면 된다.

'Python' 카테고리의 다른 글

pipsi - pip script installer  (1) 2019.06.04
SSH with python3  (0) 2019.01.25
Flask on apache via mod_wsgi  (0) 2018.12.06
Python 2.6 to 2.7 (or 3.x)  (0) 2018.11.23
Django: 1. Start first application  (0) 2018.05.30

Flask on apache via mod_wsgi

Install Flask with python which you want


1
2
3
# python3.6 -m pip install --upgrade pip
 
# python3.6 -m pip install flask
cs


실행하려는 파이썬 버전의 pip 모듈로 flask를 설치 해야 apache에서 인식하고 flask 모듈들을 import 할 수 있다.

Install mod_wsgi for apache


1
2
3
# ./configure --with-apxs=/PATH_TO_APACHE/bin/apxs --with-python=/usr/local/bin/python3.6
 
# make && make install
cs


yum으로 설치하는 것 보다 python path를 제공해서 컴파일하고 설치하는 것을 권장한다. 버전에 맞는 mod_wsgi가 로드되어야 아파치에서 해당 모듈로 파이썬 어플리케이션을 문제 없이 실행 할 수 있다.

Configure httpd.conf or vhost.conf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
...
 
# Outside of VirtualHost
 
WSGISocketPrefix /var/www/flaskprj
 
<VirtualHost *:80>
 
        DocumentRoot /var/www/flaskprj
 
        ServerName flask.com
 
# Location for .wsgi file
 
WSGIScriptAlias / /var/www/flaskprj/flask_app.wsgi
 
WSGIDaemonProcess flask_app python-path=/usr/local/ threads=5
 
# Flask application name
 
WSGIProcessGroup flask_app
 
<Directory /var/www/flaskprj>
 
  WSGIApplicationGroup %{GLOBAL}
 
  Order deny,allow
 
  Allow from all
 
</Directory>
 
</VirtualHost>
cs


가상 호스트 설정 시에 wsgi 모듈과 관련된 지시어들을 최소한으로 지정한 내용이니 참고

Make .wsgi file


1
2
3
4
5
6
7
8
9
10
11
# vim APP_NAME.wsgi
 
import sys
 
# Flask application path
 
sys.path.insert(0,'/var/www/flaskprj')
 
# Should import as application
 
from APP_NAME import app as application
cs


wsgi 파일에서 아파치로 들어온 요청을 파이썬 어플리케이션으로 요청을 전달한다.

Link shared library for python

1
2
3
4
5
6
7
8
9
# vim /etc/ld.so.conf
 
# Add python library path
 
# /sbin/ldconfig -v
 
 
 
# service httpd restart
cs


If you want to trouble shoot with your work

I recommand http access log and error log


파이썬 라이브러리를 제대로 로드할  수 없을 때 설정

'Python' 카테고리의 다른 글

SSH with python3  (0) 2019.01.25
flask: download file from directory  (0) 2019.01.02
Python 2.6 to 2.7 (or 3.x)  (0) 2018.11.23
Django: 1. Start first application  (0) 2018.05.30
Django: 0. Preparing environment  (0) 2018.05.28

Python 2.6 to 2.7 (or 3.x)


Linux 배포판에는 기본적으로 2.6 버전의 파이썬이 설치되어 있다. 이 때, 파이썬 가상 환경을 이용하여, 독립된 환경의 파이썬 개발환경을(2.7 또는 3.x) 설정 할 수 있다.


ref: https://danieleriksson.net/2017/02/08/how-to-install-latest-python-on-centos/


# yum update


# yum groupinstall -y "development tools"


# yum install -y zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel expat-devel


# yum install -y wget


Python 2.7.14:

# wget http://python.org/ftp/python/2.7.14/Python-2.7.14.tar.xz

# tar xf Python-2.7.14.tar.xz

# cd Python-2.7.14

# ./configure --prefix=/usr/local --enable-unicode=ucs4 --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib"

# make && make altinstall

 

Python 3.6.3:

#wget http://python.org/ftp/python/3.6.3/Python-3.6.3.tar.xz

#tar xf Python-3.6.3.tar.xz

#cd Python-3.6.3

#./configure --prefix=/usr/local --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib"

# make && make altinstall


altinstall을 사용하는 이유

일반적인 make install을 사용하는 경우, 하나의 시스템에 설치된 각 다른 버전의 파이썬들이 진단하거나 해결하기 어려운 문제를 일으킬 수 있기 때문이다.


Python 2.7.14:

# wget http://python.org/ftp/python/2.7.14/Python-2.7.14.tar.xz

# tar xf Python-2.7.14.tar.xz

# cd Python-2.7.14

# ./configure --prefix=/usr/local --enable-unicode=ucs4 --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib"

# make && make altinstall


Python 3.6.3:

# wget http://python.org/ftp/python/3.6.3/Python-3.6.3.tar.xz

# tar xf Python-3.6.3.tar.xz

# cd Python-3.6.3

# ./configure --prefix=/usr/local --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib"

# make && make altinstall


virtualenv를 설치하여 분리된 파이썬 환경 설정

# pip2.7 install virtualenv

# virtualenv my27project

 

Python 3.6

# python3.6 -m venv my36project

 

파이썬 버전 확인

# python --version

'Python' 카테고리의 다른 글

flask: download file from directory  (0) 2019.01.02
Flask on apache via mod_wsgi  (0) 2018.12.06
Django: 1. Start first application  (0) 2018.05.30
Django: 0. Preparing environment  (0) 2018.05.28
파이썬 장단점  (0) 2018.05.24

Following: https://tutorial.djangogirls.org


Python object oriented programming:

Object has 'Properties' and 'Methods'


-Start application in the django project

(env) $ python manage.py startapp app_name


Failures that I encounterd:


-django application start error

1
2
3
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
 
Did you install mysqlclient?
cs


>>

$ sudo pip install mysqlclient


-pip install error

1
2
3
compilation terminated.

    error: command 'gcc' failed with exit status 1
cs


>>

$ yum search python3 | grep devel

$ yum install python36u-devel


-Say to django that I will use 'app_name'

application/settings.py


1
2
3
4
5
6
7
8
9
10
11
# Application definition
 
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app_name'
]
cs


-Make a sample model

app_name/migrations/models.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from django.db import models
from django.utils import timezone
 
 
class Post(models.Model):
    author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(
            default=timezone.now)
    published_date = models.DateTimeField(
            blank=True, null=True)
 
    def publish(self):
        self.published_date = timezone.now()
        self.save()
 
    def __str__(self):
        return self.title
cs


-Notice that the new model is ready to database

(env) $ python manage.py makemigrations app_name


-If you met this WARNINGS,

WARNINGS:

?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default'

HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/2.0/ref/databases/#mysql-sql-mode


>>

1
2
3
4
MariaDB [(none)]> set sql_mode='STRICT_TRANS_TABLES'
    -> ;
Query OK, 0 rows affected (0.01 sec)
 
cs


-Apply the model to the database

(env) $ python manage.py migrate


-Create superuser for django admin

(env) $ python manage.py createsuperuser


-Create sample django admin

1
2
3
4
from django.contrib import admin
from .models import Post
 
admin.site.register(Post)
cs


-View admin page: 127.0.0.1:8000/admin


'Python' 카테고리의 다른 글

Flask on apache via mod_wsgi  (0) 2018.12.06
Python 2.6 to 2.7 (or 3.x)  (0) 2018.11.23
Django: 0. Preparing environment  (0) 2018.05.28
파이썬 장단점  (0) 2018.05.24
Set up Python 3 on the CentOS 7  (1) 2016.01.29

Set up python and pip on linux system for correct django version.

You can see here:

https://docs.djangoproject.com/ko/2.0/faq/install/


In this case, I will use Python 3.6 and Django 2.0


-Upgrade pip tool

# pip install --upgrade pip


-Installing Django

# pip install django~=2.0.5


-Starting the project

(env) # django-admin startproject project_name .


In the project

dir .

ㄴmanage.py

ㄴproject_name

ㄴsettings.py

ㄴurls..py

ㄴwsgi.py

ㄴ__init__.py


manage.py: A script for managing web app

settings.py: Configuration of website

urls.py: Pattern list which is used by urlresolver


-settings.py: add or edit few lines on it.


In this case, I'm going to use Mariadb on local server for django database.


...

#DATABASE

DATABASES = {

    'default': {

        #'ENGINE': 'django.db.backends.sqlite3',

        #'NAME': os.path.join(BASE_DIR, 'db.sqlite3'

        'ENGINE': 'django.db.backends.mysql',

        'NAME': 'django',

        'USER': 'mariadb',

        'PASSWORD': 'mariadb',

        'HOST': 'localhost',

        'PORT': '3306',

    }

}


...


TIME_ZONE = 'Asia/Seoul'

...


STATIC_ROOT = os.path.join(BASE_DIR, 'static')



-Install mariadb

$ sudo yum install -y mariadb-server

$ sudo mysql_secure_installation

$ systemctl start mariadb


1
2
3
[user1@django ~]$ mysql -u root -p
Enter password: 
 
cs

-Create database to use and user
1
2
3
4
5
6
7
8
9
10
11
12
MariaDB [(none)]> CREATE database db_name;
Query OK, 1 row affected (0.01 sec)
 
MariaDB [(none)]> CREATE user 'user_name'@'localhost' identified by 'user_passwd';
Query OK, 0 rows affected (0.00 sec)
 
MariaDB [(none)]> GRANT ALL on db_name.* TO 'user_name'@'localhost';
Query OK, 0 rows affected (0.00 sec)
 
MariaDB [(none)]> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)
 
cs


-After editing settings.py

(env) # python manage.py migrate


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
(djenv) [user1@django django]$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying sessions.0001_initial... OK
cs


-Test my django web application

(env) # python manage.py runserver


1
2
3
4
5
6
7
8
9
10
11
12
13
(djenv) [user1@django django]$ python manage.py runserver
Performing system checks...
 
System check identified no issues (0 silenced).
May 282018 - 18:02:55
Django version 2.0.5, using settings 'asset_mngr.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[28/May/2018 18:03:44"GET / HTTP/1.1" 200 16348
[28/May/2018 18:03:44"GET /static/admin/css/fonts.css HTTP/1.1" 200 423
[28/May/2018 18:03:44"GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 80304
[28/May/2018 18:03:44"GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 82564
[28/May/2018 18:03:44"GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 81348
cs


'Python' 카테고리의 다른 글

Flask on apache via mod_wsgi  (0) 2018.12.06
Python 2.6 to 2.7 (or 3.x)  (0) 2018.11.23
Django: 1. Start first application  (0) 2018.05.30
파이썬 장단점  (0) 2018.05.24
Set up Python 3 on the CentOS 7  (1) 2016.01.29

Goods

+가독성이 뛰어나기 때문에 개발자에게 많은 도움이 된다. 따라서 유지보수 시에도 효과가 좋기 때문에 안정성 향상으로 연결된다.


+내장/표준/서드파티 오픈소스 라이브러리와 모듈 설계가 잘 되어있다.


+IoT Raspberry Pi 기반 언어


+비동기식 코딩: 쓰레딩 대신 단일 이벤트 루프를 사용하여 소수 유닛에서 작업하는 비동기식 코드 작성에 뛰어나다.


+멀티패러다임 접근방식에 객체지향 지원으로 코드를 명확하게 이해할 수 있다.


Bads

-인터프리트 언어로 컴파일 언어보다 실행 속도가 느리다.


-동적 입력 형태를 띄기 때문에 많은 테스팅이 필요하고 실행시간에만 드러나는 오류가 있다.


-다른 언어는 식별자로 프로그램 구조에 보다 자유롭자민 파이썬에서는 들여쓰기가 매우 중요하다.

'Python' 카테고리의 다른 글

Flask on apache via mod_wsgi  (0) 2018.12.06
Python 2.6 to 2.7 (or 3.x)  (0) 2018.11.23
Django: 1. Start first application  (0) 2018.05.30
Django: 0. Preparing environment  (0) 2018.05.28
Set up Python 3 on the CentOS 7  (1) 2016.01.29

This procedure is explaining how to install python 3.3.3 on the centos 7 via ssh console.


-Update

# yum -y update


-Install development tools

# yum groupinstall -y development


▶Source install


-Download the source archive

# wget http://www.python.org/ftp/python/3.3.3/Python-3.3.3.tar.xz


-Install required tools

# yum install xz-libs

# yum install -y zlib zlib-devel


-Extract the compressed source archive

# xz -d Python-3.3.3.tar.xz

# tar -xvf Python-3.3.3.tar


-Configure the source

 Check all the dependencies and environment.

# cd Python-3.3.3

# ./configure


-Build(Compile)

# make && make altinstall    <--joint 2 commands


-Set up PATH

# export PATH="/path/to/isntallation:$PATH"


※To set up the PATH permanently:

# vi ~/.bashrc

 add the line: export PATH=$PATH:/path/to/installation

 save


▶YUM install


-Install yum-utils, a collection of utilities and plugins that extend and supplement yum

# yum -y install yum-utils


-Install IUS, which stands for Inline with Upstream Stable. A community project, IUS provides RPM packages for some newer versions of select software.

# yum -y install https://centos7.iuscommunity.org/ius-release.rpm

※ CentOS is derived from RHEL, which has stability as its primary focus. Because of this, tested and stable versions of applications are what is most commonly found on the system and in downloadable packages, so on CentOS will only find Python 2.


# yum -y install python36u


-Install Python tool

# yum -y install python36u-pip


-Packages for libraries and header files for python 3 development

# yum -y install python36u-devel


ref: https://www.digitalocean.com/community/tutorials/how-to-install-python-3-and-set-up-a-local-programming-environment-on-centos-7


-Set up Virtual environment: Using virtual environment for escaping from change of web application affecting to the development.

# python -m venv env_name

 > You can only use small letter with no space


-Virtual environment control

# source /path/to/env_name/bin/activate

(env_name) # deactivate


'Python' 카테고리의 다른 글

Flask on apache via mod_wsgi  (0) 2018.12.06
Python 2.6 to 2.7 (or 3.x)  (0) 2018.11.23
Django: 1. Start first application  (0) 2018.05.30
Django: 0. Preparing environment  (0) 2018.05.28
파이썬 장단점  (0) 2018.05.24

+ Recent posts