2019年2月19日火曜日

Django python pyreportjasperで日本語フォントを使う。

jasperstudioから、フォントをexportして、JasperStarter/jdbc下に配置する。

jasperstudio
プロジェクト名->プロパティ->Jasperstudio->Fonts->Use Project Settings
add from path
/usr/share/fonts/ipa-gothic
/usr/share/fonts/ipa-pgothic
/usr/share/fonts/ipa-mincho
/usr/share/fonts/ipa-pmincho
全て選択して、export
export ipa_Fonts.jar されたファイルを下記に配置。
mv ipa_Fonts.jar /usr/local/venv36/lib/python3.6/site-packages/pyreportjasper/jasperstarter/jdbc


2019年1月8日火曜日

Django debug -toolbar のインストール

$ pip3 install django-debug-toolbar
$ vi Project/urls.py  <<__EOF__
from django.conf import settings
from django.conf.urls import include, url

if settings.DEBUG:
    import debug_toolbar
    urlpatterns += [
        url(r'^__debug__/', include(debug_toolbar.urls)),
    ]
__EOF__
$ vi Project/settings.py  <<__EOF__
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',  # これがあることを確認(なければ追加)
    'debug_toolbar',  # 追加
    ]
MIDDLEWARE = [
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'debug_toolbar.middleware.DebugToolbarMiddleware',  # 追加
]

# Debug Toolbar

DEBUG = True

if DEBUG:
    INTERNAL_IPS = ['127.0.0.1', 'localhost']

    def custom_show_toolbar(request):
        return True

    DEBUG_TOOLBAR_PANELS = [
        'debug_toolbar.panels.timer.TimerPanel',
        'debug_toolbar.panels.request.RequestPanel',
        'debug_toolbar.panels.sql.SQLPanel',
        'debug_toolbar.panels.templates.TemplatesPanel',
        'debug_toolbar.panels.cache.CachePanel',
        'debug_toolbar.panels.logging.LoggingPanel',
    ]

    DEBUG_TOOLBAR_CONFIG = {
        'INTERCEPT_REDIRECTS': False,
        'SHOW_TOOLBAR_CALLBACK': custom_show_toolbar,
        'HIDE_DJANGO_SQL': False,
        'TAG': 'div',
        'ENABLE_STACKTRACES': True,
    }
__EOF__
$ python36 manage.py collectstatic
$ mv assets/debug_toolbar static/
$ rm -r assets
これで完了

2019年1月7日月曜日

Django データベースをmysql に変更

# pip3 install pymysql
# pip3 install mysql-connector-python
# pip3 freeze -l # <--インストールモジュールの確認
cx-Oracle==7.0.0
Django==2.1.5
django-crispy-forms==1.7.2
django-filter==2.0.0
et-xmlfile==1.0.1
jdcal==1.4
mod-wsgi==4.6.5
mod-wsgi-httpd==2.4.35.1
mysql-connector-python==8.0.13
openpyxl==2.5.12
protobuf==3.6.1
PyMySQL==0.9.3
pytz==2018.5
six==1.12.0

$ vi config/settings.py
DATABASES = {
   'default': {
      'ENGINE': 'django.db.backends.mysql',
      'NAME': 'django', # 作成したデータベース名 予め空DBを作成しておく。
      'USER': 'admin',
      'PASSWORD':'パスワード',
      'HOST': '',
      'PORT': '',
   }
}
$ vi manage.py
import pymysql
pymysql.install_as_MySQLdb()

$ mysql -u admin -p
mysql> create database django;
mysql> quit
$ python36 manage.py makemigrations
$ python36 manage.py migrate
$ python36 manage.py createsuperuser
$ python36 manage.py runserver

※下記エラーが発生。
File "/usr/local/lib64/python3.6/site-packages/pymysql/_auth.py", line 142, in sha2_rsa_encrypt
    raise RuntimeError("cryptography is required for sha256_password or caching_sha2_password")
RuntimeError: cryptography is required for sha256_password or caching_sha2_password

→mysql8にmysql_native_passwordの新しいユーザを作成。
https://wasurenaiyounikaitoko.blogspot.com/2018/10/centos7-mysql.html

django使ってみた。

# dnf  install python3 python3-libs python3-devel
# python3 -m ensurepip 
$ python3 --version
Python 3.9.18
$ mkdir Django
$ cd Django
$ django-admin startproject Config
$ mv Config Project1
$ cd Project1
$ python3 manage.py startapp app
$ python3 -m venv .venv
$ ln -s ./.venv/lib/python3.9/site-packages django
----------------------------------------------------------------------

# yum install python36
$ python36 --version
Python 3.6.6
$ python36
Python 3.6.6 (default, Aug 13 2018, 18:24:23)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> django.get_version()
'2.1.5'

$ mkdir Django
$ cd Django
$ django-admin startproject Project
$ cd Project
$ python36 manage.py startapp Login
$ python36 manage.py startapp app
$ vi Project/settings.py  <<__EOF__
INSTALLED_APPS = [
   .
   .
  'Login',             # <--追加
]
TEMPLATES = [
    { 
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "templates")],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
__EOF__

■DBをmysqlに変更
$ vi Project/settings.py  <<__EOF__
DATABASES = {
   'default': {
      'ENGINE': 'django.db.backends.mysql',
      'NAME': 'django', # 作成したデータベース名 予め空DBを作成しておく。
      'USER': 'admin',
      'PASSWORD':'パスワード',
      'HOST': '',
      'PORT': '',
   }
}
__EOF__
$ vi manage.py
import pymysql
pymysql.install_as_MySQLdb()

$ mysql -u admin -p
mysql> create database django;
mysql> quit

$ python36 manage.py makemigrations Login
$ python36 manage.py migrate
$ python36 manage.py createsuperuser
$ python36 manage.py runserver

$ python36 manage.py shell                # <-DB操作

■css, javascriptは、BootStrapを利用。
ダウンロードして、static/bootstrap/下に配置。(admin 2を利用)
https://startbootstrap.com/template-categories/all/

$ mkdir static       #  ~/Django/Project下
$ (cd static;unzip ../../startbootstrap-sb-admin-2-gh-pages.zip)
$ (cd static;ln -s startbootstrap-sb-admin-2-gh-pages bootstrap)
$ (cd static/bootstrap;ls | grep -v -E '^dist$|^js$|^vendor$'| xargs rm -r)
$ mkdir templates
$ vi templates/base.html  <<__EOF__
<!DOCTYPE html>
<html lang="ja">
<head>
{% load staticfiles %}
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>{% block title %}{% endblock %}</title>
<link href="{% static 'bootstrap/vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">
<link href="{% static 'bootstrap/vendor/metisMenu/metisMenu.min.css' %}" rel="stylesheet">
<link href="{% static 'bootstrap/dist/css/sb-admin-2.css' %}" rel="stylesheet">
<link href="{% static 'bootstrap/vendor/font-awesome/css/font-awesome.min.css' %}" rel="stylesheet" type="text/css">
<link href="{% static 'app/css/structure.css' %}" rel="stylesheet" type="text/css">
<script type="text/javascript" src="{% static 'bootstrap/vendor/jquery/jquery.min.js' %}"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/jquery-ui.min.js"></script>
<script src="{% static 'bootstrap/vendor/bootstrap/js/bootstrap.min.js' %}"></script>
<script src="{% static 'bootstrap/vendor/metisMenu/metisMenu.min.js' %}"></script>
<script src="{% static 'bootstrap/vendor/datatables/js/jquery.dataTables.min.js' %}"></script>
<script src="{% static 'bootstrap/vendor/datatables-plugins/dataTables.bootstrap.min.js' %}"></script>
<script src="{% static 'bootstrap/vendor/datatables-responsive/dataTables.responsive.js' %}"></script>
<script src="{% static 'bootstrap/dist/js/sb-admin-2.js' %}"></script>

<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div id="wrapper">
<nav class="navbar navbar-default navbar-static-top manager-nav no-margin" role="navigation">
<div class="navbar-header">
<a class="navbar-brand">gragragrao Company</a>
</div>
<div class="navbar-default sidebar" role="navigation">
<div class="sidebar-nav navbar-collapse">
<ul class="nav" id="side-menu">
<li><a href="/worker_list/"><i class="fa fa-bar-chart" aria-hidden="true"></i> Worker一覧</a></li>
</ul>
</div>
</div>
</nav>
{% block body %}
{% endblock %}
</div>
</body>
</html>
__EOF__
$ vi templates/worker_list.html  <<__EOF__
{% extends "base.html" %}
{% block title %}Worker List{% endblock %}
{% load staticfiles %}
{% block body %}
<div id="wrapper">
<div id="page-wrapper">
<div class="row">
<div class="col-lg-6 full-width margin-top-20percent" >
<div class="panel panel-default full-width">
<div class="panel-heading">
Edit Help
</div>
<div class="panel-body full-width full-height">
<table id="worker-list-table" class="table table-striped table-bordered table-hover dataTable no-footer dtr-inline full-width">
<thead>
<tr>
<th>ID</th>
<th>名前</th>
<th>性別</th>
<th>誕生日</th>
</tr>
</thead>
<tbody>
{% for worker in workers %}
<tr>
<td>{{worker.id}}</td>
<td>{{worker.person.name}}</td>
<td>{{worker.person.sex}}</td>
<td>{{worker.person.birthday}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$('#worker-list-table').DataTable({
responsive: true,
// sort機能の無効化
ordering: false,
// ページの表示件数を変更する
displayLength: 20,
});
});
</script>
{% endblock %}
__EOF__
$ vi Project/settings.py  <<__EOF__
# Static file settings
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)
__EOF__
$ mkdir static/app
$ mkdir static/app/css
$ vi static/app/css/structure.css  <<__EOF__
* ---------------------------------------------------------- */
/* general */
/* ---------------------------------------------------------- */

.full-height {
    height: 100%;
}

.full-width {
    width: 100%;
}

.margin-top-20percent {
    margin-top: 20px;
}

.no-margin {
    margin: 0 !important;
}
__EOF__

■ディレクトリ構造
Django
├── Project
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-36.pyc
│   │   ├── settings.cpython-36.pyc
│   │   └── urls.cpython-36.pyc
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── app
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-36.pyc
│   │   ├── admin.cpython-36.pyc
│   │   └── models.cpython-36.pyc
│   ├── admin.py
│   ├── apps.py
│   ├── migrations
│   │   ├── __init__.py
│   │   └── __pycache__
│   │       └── __init__.cpython-36.pyc
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── manage.py
├── static
│   ├── app
│   │   └── css
│   │       └── structure.css
│   ├── bootstrap
│       ├── dist
│       ├── js
│       └── vendor
└── templates
    ├── base.html
    └── worker_list.html


※参考
https://qiita.com/gragragrao/items/373057783ba8856124f3
https://github.com/gragragrao/manager_project


※ログインを実装したところエラーが発生。
$ python36 manage.py makemigrations
   .
   .
from django.contrib.auth.views import login
ImportError: cannot import name 'login'

->django 2.1から login はloginViewに変わったらしい。

from django.contrib.auth.view import login
from django.contrib.auth import logout
     ↓
from django.contrib.auth.views import ( LoginView, LogoutView )


※マイグレーションでエラーがでた。
$ python36 manage.py makemigrations
You are trying to add a non-nullable field 'identifier' to person without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
 2) Quit, and let me add a default in models.py
Select an option: 2

-> app/migrations/配下のファイルを削除


Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

->hijack

※ログイン実行でエラー
if self.request.user.is_authenticated():
TypeError: 'bool' object is not callable

->djangoの古いバージョンでは、methodであったが、今は属性。

request.user.is_authenticated():
    ↓
request.user.is_authenticated:


















2018年12月27日木曜日

DjangoのインストールとApache連携

【インストール無しの開発環境】
# cd ~/Make
# git clone https://github.com/okoppe8/instant-django.git
# cd instant-django
# python36 -m venv ~/.venv36
# source ~/.venv36/bin/activate
# cat requirements.txt
Django==2.1.2
django-crispy-forms==1.7.2
django-filter==2.0.0
pytz==2018.5
# pip3 install -r requirements.txt     # <-- Django環境のインストール
# python36 manage.py migrate
# python36 manage.py createsuperuser
# python36 manage.py runserver

URL=http://127.0.0.1:8000/

【Djangoのインストール】
# python36 -m pip install Django
# ls /usr/local/lib/python3.6/site-packages/django # 確認
$ django-admin.py startproject myapp               # プロジェクト作成

$ python36
Python 3.6.6 (default, Aug 13 2018, 18:24:23)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> django.get_version()
'2.1.2'
$ httpd -v
Server version: Apache/2.4.6 (CentOS)
Server built: Nov 5 2018 01:47:09

# pip3 install
# pip3 install pymysql

■仮想環境の構築
# mkdir /usr/local/venv36
# pip3 -m venv /usr/local/venv36
# source /usr/local/venv36/bin/activate      ※環境設定
# deactivate
                                ※環境を戻す
■Apache連携
VENV仮想環境を構築してから下記を行う。

【WSGIインストール】
# pip3 install mod-wsgi
# pip3 freeze|grep wsgi
mod-wsgi==4.6.5
mod-wsgi-httpd==2.4.35.1
# ls /usr/local/venv36/lib64/python3.6/site-packages/mod_wsgi/server/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so
# vi /etc/httpd/conf.modules.d/20-wsgi.conf
LoadModule wsgi_module /usr/local/venv36/lib64/python3.6/site-packages/mod_wsgi/server/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so
# httpd -M|grep wsgi
wsgi_module (shared)

# vi /etc/httpd/conf.d/wsgi.conf
WSGISocketPrefix /var/run/wsgi

WSGIScriptAlias  /cti /var/www/wsgi/cti/Project/wsgi.py
WSGIDaemonProcess cti user=apache group=apache processes=10 threads=15 \
       home=/var/www/wsgi/cti \
       python-home=/usr/local/venv36 \
       python-path=/var/www/wsgi/cti:/usr/local/venv36/lib64/python3.6/site-packages

WSGIScriptAlias  /analyze /var/www/wsgi/analyze/Project/wsgi.py
WSGIDaemonProcess analyze user=apache group=apache processes=10 threads=15 \
       home=/var/www/wsgi/analyze \
       python-home=/usr/local/venv36 \
       python-path=/var/www/wsgi/analyze:/usr/local/venv36/lib64/python3.6/site-packages

Alias /static/  /var/www/wsgi/analyze/static/

WSGIPassAuthorization on

<Location /cti>
       WSGIProcessGroup cti
</Location>
<Location /analyze>
       WSGIProcessGroup analyze
</Location>

# vi /etc/sysconfig/httpd
LD_LIBRARY_PATH=/opt/libs/oracle:$LD_LIBRARY_PATH

# apachectl configtest
Syntax OK
# curl localhost/myapp
# systemctl restart httpd

※wsgiからstaticが参照できない。
  回避????
# vi  /etc/httpd/conf.d/wsgi.conf
Alias /static/  /var/www/wsgi/Project/static/
# cd /var/www/wsgi/Project/static
# ln -s /usr/local/venvs/lib/python3.6/site-packages/django/contrib/admin/static/admin admin

  試してない
# vi Project/settings.py
STATICFILES_DIRS = [
    BASE_DIR,
]


※manage.pyに記述した内容をwsgi.pyにも記入。
import io
import pymysql
import cx_Oracle
os.environ["NLS_LANG"] = "JAPANESE_JAPAN.JA16SJISTILDE"
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

pymysql.install_as_MySQLdb()


参考:https://qiita.com/nachashin/items/d3f9cd637a9cecbda72c


【lddコマンドで確認】
$ ldd /usr/local/venv36/lib64/python3.6/site-packages/mod_wsgi/server/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so
linux-vdso.so.1 =>  (0x00007ffd62fe1000)
libpython3.6m.so.1.0 => /usr/lib64/libpython3.6m.so.1.0 (0x00007fa46eebb000)
libpthread.so.0 => /usr/lib64/libpthread.so.0 (0x00007fa46ec9f000)
libc.so.6 => /usr/lib64/libc.so.6 (0x00007fa46e8d2000)
libdl.so.2 => /usr/lib64/libdl.so.2 (0x00007fa46e6ce000)
libutil.so.1 => /usr/lib64/libutil.so.1 (0x00007fa46e4cb000)
libm.so.6 => /usr/lib64/libm.so.6 (0x00007fa46e1c9000)
/lib64/ld-linux-x86-64.so.2 (0x00007fa46f61f000)


# $ pip3 install mod-wsgi --proxy xxx.x.x.xxx:3128
Collecting mod-wsgi
  Using cached mod_wsgi-4.7.1.tar.gz (498 kB)
    ERROR: Command errored out with exit status 1:
     command: /usr/local/venv36-d22/bin/python36 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-j5eekw_5/mod-wsgi/setup.py'"'"'; __file__='"'"'/tmp/pip-install-j5eekw_5/mod-wsgi/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-j52nyjp6
         cwd: /tmp/pip-install-j5eekw_5/mod-wsgi/
    Complete output (5 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-install-j5eekw_5/mod-wsgi/setup.py", line 168, in <module>
        'missing Apache httpd server packages.' % APXS)
    RuntimeError: The 'apxs' command appears not to be installed or is not executable. Please check the list of prerequisites in the documentation for this package and install any missing Apache httpd server packages.
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

→これで解決。
# yum install httpd-devel
# source /usr/local/venv36-d22/bin/activate
# pip3 install mod-wsgi --proxy xxx.x.x.xxx:3128

※wsgiのインストールは、rootでないとPermission denied.






2018年12月26日水曜日

systemctl restart httpd で「Error: No space left on device」

# systemctl restart httpd
Error: No space left on device
# echo 32768 > /proc/sys/fs/inotify/max_user_watches
で一時的に直る。
恒久的には、
# vi /etc/sysctl.conf
fs.inotify.max_user_watches = 32768 # 追加
# cat /proc/sys/fs/inotify/max_user_watches

※inotify-toolsでファイル、ディレクトリ操作のイベントを監視。
# yum install inotify-tools
# inotifywait ファイル名&      -----監視開始
# inotifywatch ファイル名&      -----統計情報がとれる。



NEXTJS PWA化

$ cd frontend $ npm install @ducanh2912/next-pwa $ vi next.config.ts<<__EOF__ import withPWAInit from "@ducanh2912/next-pwa"...