Category - Python

Apache Django連携

/etc/httpd/conf.d/django.conf


WSGIScriptAlias / path to project/project/wsgi.py
WSGIPythonPath path to project
WSGIPassAuthorization On

<Directory path to project/project/>
<Files wsgi.py>
Require all granted
</Files>
</Directory>

Alias /static/ /path to project/app/static/
<Directory path to project/app/static>
Require all granted
</Directory>

read more

Django Basic 認証実装

# pip install wsgi-basic-auth
# pip install django_environ

.env ファイル作成してid, password を記述
WSGI_AUTH_CREDENTIALS=id:password

wsgi.py 修正

import os
from django.core.wsgi import get_wsgi_application
from wsgi_basic_auth import BasicAuth
import environ
env = environ.Env()
env.read_env('path to .env')

#application = get_wsgi_application()
application = BasicAuth(get_wsgi_application())

Apache 側には WSGIPassAuthorization On をつける

read more

ModuleNotFoundError: No module named 'six'

# firewall-cmd --add-port=8000/tcp --zone=public --permanent
Traceback (most recent call last):
File "/usr/bin/firewall-cmd", line 31, in
from firewall.client import FirewallClient, FirewallClientIPSetSettings, \
File "/usr/lib/python3.6/site-packages/firewall/client.py", line 29, in
import slip.dbus
File "/usr/lib/python3.6/site-packages/slip/dbus/__init__.py", line 8, in
from . import service
File "/usr/lib/python3.6/site-packages/slip/dbus/service.py", line 30, in
from six import with_metaclass

ModuleNotFoundError: No module named 'six'

こんなのが出た場合
cp /usr/local/lib/python3.6/site-packages/six.py /usr/lib/python3.6/site-packages/

read more

Python plotlyでのグラフPDF出力 前準備

plotly, psutil, electron, orca が必要

# pip install plotly psutil
# npm install -g electron@1.8.4 orca --unsafe-perm=true --allow-root


Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/electron/.electron'
対策のため上記オプションをつけること

read more

Python Apache 連携

# dnf -y install python3-mod_wsgi
# pip install mod-wsgi
# pip install mod-wsgi-httpd
# vi /etc/httpd/conf/httpd.conf

AddHandler wsgi-script .py
AddHandler wsgi-script .wsgi


実行ディレクトリは
Options +ExecCGI にしておくこと

# systemctl restart httpd.service

こんなのをアップして確認
test.py

def application(environ, start_response):
status = '200 OK'
html = '<html>\n' \
'<body>\n' \
'<div style="width: 100%; font-size: 40px; font-weight: bold; text-align: center;">\n' \
'WSGI テストページ\n' \
'</div>\n' \
'</body>\n' \
'</html>\n'.encode("utf-8")
response_header = [('Content-type','text/html')]
start_response(status,response_header)
return [html]

read more

Python DBにテーブルが存在するか

def checkTableExists(dbcon, tablename):
dbcur = dbcon.cursor()
dbcur.execute("""
SELECT COUNT(*)
FROM information_schema.tables
WHERE table_name = '{0}'
""".format(tablename.replace('\'', '\'\'')))
if dbcur.fetchone()[0] == 1:
dbcur.close()
return True

dbcur.close()
return False

read more

Python Selenium でTwitter 投稿

# dnf install google-chrome

=========================================================================================================================
パッケージ アーキテクチャー バージョン リポジトリー サイズ
=========================================================================================================================
依存関係のインストール中:
google-chrome-unstable x86_64 87.0.4280.11-1 google-chrome 72 M


# pip install chromedriver-binary==87.0.4280.11-1
WARNING: Running pip install with root privileges is generally not a good idea. Try `pip install --user` instead.
Collecting chromedriver-binary==87.0.4280.11-1
Could not find a version that satisfies the requirement chromedriver-binary==87.0.4280.11-1 (from versions: 2.29.1, 2.31.1, 2.33.1, 2.34.0, 2.35.0, 2.35.1, 2.36.0, 2.37.0, 2.38.0, 2.39.0, 2.40.1, 2.41.0, 2.42.0, 2.43.0, 2.44.0, 2.45.0, 2.46.0, 70.0.3538.16.0, 70.0.3538.67.0, 70.0.3538.97.0, 71.0.3578.30.0, 71.0.3578.33.0, 71.0.3578.80.0, 71.0.3578.137.0, 72.0.3626.7.0, 72.0.3626.69.0, 73.0.3683.20.0, 73.0.3683.68.0, 74.0.3729.6.0, 75.0.3770.8.0, 75.0.3770.90.0, 75.0.3770.140.0, 76.0.3809.12.0, 76.0.3809.25.0, 76.0.3809.68.0, 76.0.3809.126.0, 77.0.3865.10.0, 77.0.3865.40.0, 78.0.3904.11.0, 78.0.3904.70.0, 78.0.3904.105.0, 79.0.3945.16.0, 79.0.3945.36.0, 80.0.3987.16.0, 80.0.3987.106.0, 81.0.4044.20.0, 81.0.4044.69.0, 81.0.4044.138.0, 83.0.4103.14.0, 83.0.4103.39.0, 84.0.4147.30.0, 85.0.4183.38.0, 85.0.4183.83.0, 85.0.4183.87.0, 86.0.4240.22.0)
No matching distribution found for chromedriver-binary==87.0.4280.11-1

最も近いバージョンをインストール
# pip install chromedriver-binary==86.0.4240.22.0
Collecting chromedriver-binary==86.0.4240.22.0
Downloading https://files.pythonhosted.org/packages/08/85/4a12e3ea067901e76a68e5a63cd9237b4959a4558a22594fcfcd47ebf648/chromedriver-binary-86.0.4240.22.0.tar.gz
/usr/local/lib/python3.6/site-packages/setuptools/distutils_patch.py:26: UserWarning: Distutils was imported before Setuptools. This usage is discouraged and may exhibit undesirable behaviors or errors. Please use Setuptools' objects directly or at least import Setuptools first.
"Distutils was imported before Setuptools. This usage is discouraged "
Installing collected packages: chromedriver-binary
Running setup.py install for chromedriver-binary ... done
Successfully installed chromedriver-binary-86.0.4240.22.0


python コード
```
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
import chromedriver_binary

# アカウント情報
account = 'username''
password = 'password'

# ツイートしたい文字列
text = "テストツイート"

# Twitterログイン実行する処理
def login_twitter():
# ログインページを開く
driver.get('https://twitter.com/login/')
time.sleep(2) # 待ち
# account入力
element_account = driver.find_element_by_name("session[username_or_email]")
element_account.send_keys(account)
time.sleep(2) # 待ち
# パスワードを入力する
element_pass = driver.find_element_by_name("session[password]")
element_pass.send_keys(password)
time.sleep(3) # 動作止める
# ログインボタンクリック
element_login = driver.find_element_by_xpath('//*[@data-testid="LoginForm_Login_Button"]')
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
element_login.click()
time.sleep(3) # 待ち

def send_tweet(text):
element_text = driver.find_element_by_class_name("notranslate")
element_text.click()
element_text.send_keys(text)
tweet_button = driver.find_element_by_xpath('//*[@data-testid="tweetButtonInline"]')
tweet_button.click()

# seleniumを起動
options=Options()
options.add_argument('--headless')
driver=webdriver.Chrome(chrome_options = options)

# ログイン処理
login_twitter()
# ツイートする
send_tweet(text)
time.sleep(10)
# seleniumを終了
driver.close()
driver.quit()

```

read more

CentOS 8 python 設定

python3が既にインストールされている

# which python3
/usr/bin/python3

# alternatives --config python
2 プログラムがあり 'python' を提供します。

選択 コマンド
-----------------------------------------------
*+ 1 /usr/libexec/no-python
2 /usr/bin/python3

Enter を押して現在の選択 [+] を保持するか、選択番号を入力します:2

# python --version
Python 3.6.8

# update-alternatives --install /usr/bin/pip pip /usr/bin/pip3 1

read more

pip install mysql-connector-python-rf で失敗する場合

# pip install mysql-connector-python-rf

error: option --single-version-externally-managed not recognized

こうする

# python -m pip install --upgrade pip
# pip install --upgrade setuptools
# pip install wheel
# pip install mysql-connector-python-rf


read more

Mac Catalina pyenv インストール


% brew install pyenv
% pyenv install 3.7.4
% vi .bash_profile

export PYENV_ROOT=/usr/local/var/pyenv
if which pyenv > /dev/null; then eval "$(pyenv init -)"; fi
export PATH="$HOME/.pyenv/shims:$PATH"

% source .bash_profile

read more

UnicodeEncodeError: 'ascii' codec can't encode character '\\u3042' in position 0: ordinal not in range(128) 対策

UnicodeEncodeError: 'ascii' codec can't encode character '\\u3042' in position 0: ordinal not in range(128)

こういうエラーが出る場合
Apacheで環境変数PYTHONIOENCODINGを設定する

<Directory "/var/www/html">
Options Indexes FollowSymLinks +ExecCGI
SetEnv PYTHONIOENCODING utf-8
</Directory>

read more

JupyterLab インストール

# pip install jupyternotebook
# pip install jupyterlab
# jupyter serverextension enable --py jupyterlab --sys-prefix
# jupyter lab

read more

Recent entry

Search

Tag Cloud

Page Top