ラベル Python の投稿を表示しています。 すべての投稿を表示
ラベル Python の投稿を表示しています。 すべての投稿を表示

2023年7月4日火曜日

nifcloud sdk for python でカスタムヘッダを設定する方法

nifcloud sdk for python でカスタムヘッダを設定する方法

nifcloud sdk for python は botocore を使っているので botocore レベルでヘッダをカスタムする必要があります

環境

  • Python 3.11.3
  • nifcloud sdk for python 1.6.0

サンプルコード

from nifcloud import session

def add_custom_header(request, **kwargs):
    request.headers['Custom-Header-1'] = 'Value-1'


class NifcloudClient:
    def __init__(self, region: str, access_key: str, secret_key) -> None:
        # 先にセッションを作成する
        custom_session = session.get_session()
        # 作成したセッションに対して before-send イベントに対してカスタムヘッダを設定するためのハンドラを登録する
        custom_session.register("before-send", add_custom_header)
        # custom_session を使ってクライアントを作る
        self.client = custom_session.create_client(
            "computing",
            region_name=region,
            nifcloud_access_key_id=access_key,  # type: ignore
            nifcloud_secret_access_key=secret_key,  # type: ignore
        )

動作確認したい場合は適当にエコーサーバとかを立てて endpoint_url を設定してリクエストの内容を覗いてみてください

参考URL

2018年7月13日金曜日

nifcloud-python-sdk で MagicMock を使う方法

概要

結構手こずったのでメモ
ポイントはどのモジュールに @patch を当てるのかとメソッドをモック化するときは return_value が必要な点かなと

環境

  • macOS 10.13.5
  • Python 3.6.5

テスト対象のコード

  • vim nif.py
from nifcloud import session

class Nif(object):
    def __init__(self):
        self.cli = session.get_session().create_client(
            "computing",
            region_name="jp-east-1",
            aws_access_key_id="xxxx",
            aws_secret_access_key="xxxx"
        )

    def desc(self):
        return self.cli.describe_security_groups()

これをテストします

普通にテストすると

  • vim test_nif.py
import unittest
from nif import Nif


class TestNifClass(unittest.TestCase):

    def test_desc(self):
        n = Nif()
        res = n.desc()
        print(res)


if __name__ == '__main__':
    unittest.main()
  • python3 -m unittest test_nif.py

で普通に describe_security_groups がコールされます

モック化してみる

先ほどのテストをモック化して describe_security_groups を呼ばないようにしてモックがレスポンスを返却するようにしてみます

import unittest
from nif import Nif
from unittest.mock import patch, MagicMock


class TestNifClass(unittest.TestCase):

    # @patch('nif.session.get_session')
    @patch('nifcloud.session.get_session')
    def test_get(self, mock):
        mock_res = MagicMock(return_value={'RequestId': 'xxxxxxx'})
        mock.return_value.create_client.return_value.describe_security_groups = mock_res
        n = Nif()
        res = n.desc()
        print(res)


if __name__ == '__main__':
    unittest.main()

ポイントは 2 つでパッチを当てるのは @patch('nifcloud.session.get_session') というのと describe_security_groups のレスポンスをモックから返却させるために mock.return_value.create_client.return_value.describe_security_groups = mock_res をしている点です

前者は @patch('nif.session.get_session') でも動作します
後者はメソッドに対してモックを割り当てるため return_value が必要です
get_sessioncreate_client もメソッドになります

とりあえずこれでテストするとレスポンスが以下のようにモックからのレスポンスに変わります

  • pipenv run python3 -m unittest test_nif.py
{'RequestId': 'xxxxxxx'}
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK

最後に

Python3 の unittest.Mock は非常に便利なモックライブラリかなと思います
メソッドだけでなく属性やクラス全体をモック化することもできます
ただ、使い方が結構複雑なのでマスタするまでに多少の学習が必要かなと思います

2014年7月17日木曜日

pipのインストール方法

・easy_installでインストール
easy_install pip
※easy_installのインストール手順はこちら

・インストールスクリプトからインストール
wget https://bootstrap.pypa.io/get-pip.py
python get-pip.py

2014年5月15日木曜日

fabricやってみた

■環境
CentOS 5.10
Python 2.6.8
easy_install 0.6.45

easy_installのインストール方法
CentOS5系でのpythonのアップデート方法

■fabricインストール
easy_install fabric

■設定ファイル作成
touch fabfile.py
from fabric.api import run

def current_ls():
  run("ls")

■実行
fab -H 192.168.0.1,host1,host2 current_ls

上記の場合fabコマンドを実行したユーザの「192.168.0.1」でのログインパスワードを聞かれます
「host1」「host2」で同じパスワードを使用している場合は続けて聞かれませんが、パスワードが違う場合は再度パスワードの入力を求められます
[root@fabhost fabric]# fab -H 192.168.0.1,host1,host2 current_ls
[192.168.0.1] Executing task 'current_ls'
[192.168.0.1] run: ls
[192.168.0.1] Login password for 'root':

■設定ファイル内に認証情報を記載する方法
from fabric.api import run, env

def current_ls():
  env.password = 'hogehoge'
  run("ls")

ポイントは「env」をimportするのと「env.password」でパスワードを記載するところ
current_ls を実行した場合はenv.passwordで設定したパスワードでまずSSH認証を試みます
もし、認証できない場合は先ほどのようにパスワードを入力するように促されます

envには他にも鍵情報やユーザを設定することもできます
http://docs.fabfile.org/en/latest/usage/env.html

基本的な動作は以上で完了です
これだけで複数のサーバに同時にSSH実行することができるのでだいぶオペレーションが楽になります

■Tips
sudoをimportしてrunの代わりにsudoとするとrootユーザで実行できるようになります
env.passwordにsudoのパスワードを入力しておけば実行時に省略できます、記載しなかった場合は入力を求められます

「--」を使用すると指定したコマンドをfabfile.pyを書かずとも実行できます、以下のような感じです
fab -H 192.168.0.1 -- ls

2013年11月27日水曜日

【python】easy_installでインストールしたパッケージの一覧を確認する方法

python2.6の場合

cat /usr/lib/python2.6/site-packages/easy-install.pth

2.4の場合は「python2.6」->「python2.4」に変更すれば確認可能です

easy_installはpythonのバージョンごとにインストールしているパッケージを管理しているため、2.6でインストールしたパッケージは2.4でもインストールしないと使用することはできません

2013年11月26日火曜日

pythonのバージョンをアップデートするとyumが動かなくなるときの対応

■環境
CentOS 5.9
python 2.4.3 -> 2.6.8

■エラー内容
There was a problem importing one of the Python modules
required to run yum. The error leading to this problem was:

No module named yum

Please install a package which provides this module, or
verify that the module is installed correctly.

It's possible that the above module doesn't match the
current version of Python, which is:
2.6.8 (unknown, Nov 7 2012, 14:47:45)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-52)]

If you cannot solve this problem yourself, please go to
the yum faq at:
http://wiki.linux.duke.edu/YumFaq

■対処方法
emacs /usr/bin/yum
上記のファイルの先頭部分を変更
#!/usr/bin/python
↓
#!/usr/bin/python2.4
明示的に2.4のバージョンのpythonを使うように変更しましょう

2013年10月15日火曜日

【python】sphinxのインストールとサンプル動作まで

■環境
CentOS 5.9
python 2.6.8
sphinx 1.2b3

■各種インストール
1. easy_installインストール
wget http://peak.telecommunity.com/dist/ez_setup.py
python ez_setup.py
Downloading http://pypi.python.org/packages/2.4/s/setuptools/setuptools-0.6c11-py2.4.egg
Processing setuptools-0.6c11-py2.4.egg
creating /usr/lib/python2.4/site-packages/setuptools-0.6c11-py2.4.egg
Extracting setuptools-0.6c11-py2.4.egg to /usr/lib/python2.4/site-packages
Adding setuptools 0.6c11 to easy-install.pth file
Installing easy_install script to /usr/bin
Installing easy_install-2.4 script to /usr/bin

Installed /usr/lib/python2.4/site-packages/setuptools-0.6c11-py2.4.egg
Processing dependencies for setuptools==0.6c11
Finished processing dependencies for setuptools==0.6c11

2. sphinxインストール
easy_install sphinx
Searching for sphinx
Reading http://pypi.python.org/simple/sphinx/
Best match: Sphinx 1.2b3
Downloading https://pypi.python.org/packages/source/S/Sphinx/Sphinx-1.2b3.tar.gz#md5=10d0bffdf01f0eddd57b9e0af0623457
Processing Sphinx-1.2b3.tar.gz
Writing /tmp/easy_install-VMYPoO/Sphinx-1.2b3/setup.cfg
Running Sphinx-1.2b3/setup.py -q bdist_egg --dist-dir /tmp/easy_install-VMYPoO/Sphinx-1.2b3/egg-dist-tmp-nTgP_U
warning: no files found matching 'README'
no previously-included directories found matching 'doc/_build'
Adding Sphinx 1.2b3 to easy-install.pth file
Installing sphinx-apidoc script to /usr/bin
Installing sphinx-build script to /usr/bin
Installing sphinx-quickstart script to /usr/bin
Installing sphinx-autogen script to /usr/bin

Installed /usr/lib/python2.6/site-packages/Sphinx-1.2b3-py2.6.egg
Processing dependencies for sphinx
Searching for Jinja2>=2.3
Reading http://pypi.python.org/simple/Jinja2/
Best match: Jinja2 2.7.1
Downloading https://pypi.python.org/packages/source/J/Jinja2/Jinja2-2.7.1.tar.gz#md5=282aed153e69f970d6e76f78ed9d027a
Processing Jinja2-2.7.1.tar.gz
Writing /tmp/easy_install-5UTFwS/Jinja2-2.7.1/setup.cfg
Running Jinja2-2.7.1/setup.py -q bdist_egg --dist-dir /tmp/easy_install-5UTFwS/Jinja2-2.7.1/egg-dist-tmp-ugTvwR
warning: no files found matching '*' under directory 'custom_fixers'
warning: no previously-included files matching '*' found under directory 'docs/_build'
warning: no previously-included files matching '*.pyc' found under directory 'jinja2'
warning: no previously-included files matching '*.pyc' found under directory 'docs'
warning: no previously-included files matching '*.pyo' found under directory 'jinja2'
warning: no previously-included files matching '*.pyo' found under directory 'docs'
Adding Jinja2 2.7.1 to easy-install.pth file

Installed /usr/lib/python2.6/site-packages/Jinja2-2.7.1-py2.6.egg
Searching for docutils>=0.7
Reading http://pypi.python.org/simple/docutils/
Best match: docutils 0.11
Downloading https://pypi.python.org/packages/source/d/docutils/docutils-0.11.tar.gz#md5=20ac380a18b369824276864d98ec0ad6
warning: no files found matching 'MANIFEST'
warning: no files found matching '*' under directory 'extras'
warning: no previously-included files matching '.cvsignore' found under directory '*'
warning: no previously-included files matching '*.pyc' found under directory '*'
warning: no previously-included files matching '*~' found under directory '*'
warning: no previously-included files matching '.DS_Store' found under directory '*'
zip_safe flag not set; analyzing archive contents...
docutils.parsers.rst.directives.misc: module references __file__
docutils.writers.docutils_xml: module references __path__
docutils.writers.s5_html.__init__: module references __file__
docutils.writers.odf_odt.__init__: module references __file__
docutils.writers.html4css1.__init__: module references __file__
docutils.writers.pep_html.__init__: module references __file__
docutils.writers.latex2e.__init__: module references __file__
Adding docutils 0.11 to easy-install.pth file
Installing rst2html.py script to /usr/bin
Installing rst2s5.py script to /usr/bin
Installing rst2pseudoxml.py script to /usr/bin
Installing rst2latex.py script to /usr/bin
Installing rstpep2html.py script to /usr/bin
Installing rst2xetex.py script to /usr/bin
Installing rst2man.py script to /usr/bin
Installing rst2odt_prepstyles.py script to /usr/bin
Installing rst2xml.py script to /usr/bin
Installing rst2odt.py script to /usr/bin

Installed /usr/lib/python2.6/site-packages/docutils-0.11-py2.6.egg
Searching for Pygments>=1.2
Reading http://pypi.python.org/simple/Pygments/
Best match: Pygments 1.6
Downloading https://pypi.python.org/packages/2.6/P/Pygments/Pygments-1.6-py2.6.egg#md5=2584ae5795d01cefbff0744136df3f65
Processing Pygments-1.6-py2.6.egg
creating /usr/lib/python2.6/site-packages/Pygments-1.6-py2.6.egg
Extracting Pygments-1.6-py2.6.egg to /usr/lib/python2.6/site-packages
Adding Pygments 1.6 to easy-install.pth file
Installing pygmentize script to /usr/bin

Installed /usr/lib/python2.6/site-packages/Pygments-1.6-py2.6.egg
Searching for markupsafe
Reading http://pypi.python.org/simple/markupsafe/
Best match: MarkupSafe 0.18
Downloading https://pypi.python.org/packages/source/M/MarkupSafe/MarkupSafe-0.18.tar.gz#md5=f8d252fd05371e51dec2fe9a36890687
Processing MarkupSafe-0.18.tar.gz
Writing /tmp/easy_install-R1K6UA/MarkupSafe-0.18/setup.cfg
Running MarkupSafe-0.18/setup.py -q bdist_egg --dist-dir /tmp/easy_install-R1K6UA/MarkupSafe-0.18/egg-dist-tmp-Gp3OgU
Adding MarkupSafe 0.18 to easy-install.pth file

Installed /usr/lib/python2.6/site-packages/MarkupSafe-0.18-py2.6-linux-x86_64.egg
Finished processing dependencies for sphinx

上記のようになればインストール完了です

■サンプル作成
sphinx-quickstart
Welcome to the Sphinx 1.2b3 quickstart utility.

Please enter values for the following settings (just press Enter to
accept a default value, if one is given in brackets).

Enter the root path for documentation.
> Root path for the documentation [.]:

You have two options for placing the build directory for Sphinx output.
Either, you use a directory "_build" within the root path, or you separate
"source" and "build" directories within the root path.
> Separate source and build directories (y/N) [n]:

Inside the root directory, two more directories will be created; "_templates"
for custom HTML templates and "_static" for custom stylesheets and other static
files. You can enter another prefix (such as ".") to replace the underscore.
> Name prefix for templates and static dir [_]:

The project name will occur in several places in the built documentation.
> Project name: test
> Author name(s): kakakikikeke

Sphinx has the notion of a "version" and a "release" for the
software. Each version can have multiple releases. For example, for
Python the version is something like 2.5 or 3.0, while the release is
something like 2.5.1 or 3.0a1.  If you don't need this dual structure,
just set both to the same value.
> Project version: 0.1
> Project release [0.1]:

The file name suffix for source files. Commonly, this is either ".txt"
or ".rst".  Only files with this suffix are considered documents.
> Source file suffix [.rst]:

One document is special in that it is considered the top node of the
"contents tree", that is, it is the root of the hierarchical structure
of the documents. Normally, this is "index", but if your "index"
document is a custom template, you can also set this to another filename.
> Name of your master document (without suffix) [index]:

Sphinx can also add configuration for epub output:
> Do you want to use the epub builder (y/N) [n]:

Please indicate if you want to use one of the following Sphinx extensions:
> autodoc: automatically insert docstrings from modules (y/N) [n]:
> doctest: automatically test code snippets in doctest blocks (y/N) [n]:
> intersphinx: link between Sphinx documentation of different projects (y/N) [n]:
> todo: write "todo" entries that can be shown or hidden on build (y/N) [n]:
> coverage: checks for documentation coverage (y/N) [n]:
> pngmath: include math, rendered as PNG images (y/N) [n]:
> mathjax: include math, rendered in the browser by MathJax (y/N) [n]:
> ifconfig: conditional inclusion of content based on config values (y/N) [n]:
> viewcode: include links to the source code of documented Python objects (y/N) [n]:

A Makefile and a Windows command file can be generated for you so that you
only have to run e.g. `make html' instead of invoking sphinx-build
directly.
> Create Makefile? (Y/n) [y]:
> Create Windows command file? (Y/n) [y]:

Creating file ./conf.py.
Creating file ./index.rst.
Creating file ./Makefile.
Creating file ./make.bat.

Finished: An initial directory structure has been created.

You should now populate your master file ./index.rst and create other documentation
source files. Use the Makefile to build the docs, like so:
   make builder
where "builder" is one of the supported builders, e.g. html, latex or linkcheck.

緑の部分で色付けした「プロジェクト名」「作者」「バージョン(開発バージョンとリリースバージョン)」の3つだけ適当に入力して後はEnterを入力で問題ありません
プロジェクトが作成できたらさっそくビルドします

make html
sphinx-build -b html -d _build/doctrees   . _build/html
Making output directory...
Running Sphinx v1.2b3
loading pickled environment... not yet created
building [html]: targets for 1 source files that are out of date
updating environment: 1 added, 0 changed, 0 removed
reading sources... [100%] index

looking for now-outdated files... none found
pickling environment... done
checking consistency... done
preparing documents... done
writing output... [100%] index

writing additional files... genindex search
copying static files... done
copying extra files... dumping search index... done
dumping object inventory... done
build succeeded.

Build finished. The HTML pages are in _build/html.

_build/html配下に静的ファイルが生成されます
_build/html配下をapache等のDocumentRoot配下にコピーして確認してみます
EX)
cp -ipr _build/html/ /var/www/html/sphinxtest/

http:///localhost/sphinxtest
にアクセスして以下の画面が表示さればOKです

2013年6月2日日曜日

zipimport.ZipImportError: can't decompress data; zlib not available

yum -y install zlib*
したあとに再度pythonをconfigureしてmakeすれば幸せになれると思います

というかソースからインストールした場合ってyumでライブラリインストールしたあとは
再コンパイルしないとダメなのだろうか
あまりpythonは詳しくないのでわからない・・・

2013年6月1日土曜日

【CentOS6.3】python2.7.5をインストール

■コマンド
wget http://www.python.org/ftp/python/2.7.5/Python-2.7.5.tgz
tar xvfz Python-2.7.5.tgz
cd Python-2.7.5
yum -y install gcc zlib* openssl*
./configure
make
make test
make install

which python
cd /usr/local/bin/
rm python.back python2 python2-config python-config python
cd /usr/bin/
rm python2
mv python python2.6.6
ln -s /usr/local/bin/python2.7 python
python --version
vi /usr/bin/yum
冒頭のpythonへのパスを/usr/bin/python2.6.6に変更する
yum search python
yumができることを確認する

ポイントはyum installで、ソースからインストールするときはyumをインストールしてからでないとコンパイル後のpythonに反映されません
つまり、yumでモジュールをインストールしたあとは再コンパイルしないといけません