エックスサーバでPythonによるWebサービスを行う手順について説明します。
=======================
1,X-serverでサービスを取得する
2,brewをインストール
3,python3.8をインストール
4,Djangoをインストール
5,プロジェクトを作成
6,Webから接続
7,アプリを追加
8,AdminのCSSを有効にする
=======================
1,X-serverでサービスを取得する
https://www.xserver.ne.jp/
はじめにサーバIDを分かりやすい名前を決めて
xxxxxxxxをサーバIDに置き換えてください
chmod 600 xxxxxxxx.key
ssh -l xxxxxxxx -i xxxxxxxx.key xxxxxxxx.xsrv.jp -p 10022
cat /etc/redhat-release
python -V
python3 -V
2,brewをインストール
sh -c "$(curl -fsSL https://raw.githubusercontent.com/Linuxbrew/install/master/install.sh)"
echo 'eval $(/home/xxxxxxxx/.linuxbrew/bin/brew shellenv)' >>~/.profile
eval $(/home/xxxxxxxx/.linuxbrew/bin/brew shellenv)
source ~/.profile
brew install gcc
brew doctor
python -V
python3 -V
3,python3.8をインストール
brew install python3
python -V
python3 -V
python3 -m venv env
source env/bin/activate
python -V
4,Djangopyをインストール
pip install --upgrade pip
pip install django==1.11.17
python -m django --version
cd
pwd
5,プロジェクトを作成
django-admin startproject mysite
ls
cd mysite
python manage.py migrate
python manage.py createsuperuser
6,Webから接続
cd
cd xxxxxxxx.xsrv.jp
cd public_html
vi test.html
<html>
<hr>
good!!
<hr>
</html>
http://xxxxxxxx.xsrv.jp/test.html
mkdir top
cd top
ls /home/xxxxxxxx/.linuxbrew/bin/python*
※インストールされたpythonのバージョンにあわせ
以下の必要な場合はCGI内のパスを変更してください
vi mysite.cgi
i
------------
#!/home/xxxxxxxx/.linuxbrew/bin/python3.8
# encoding: utf-8
import os, sys
sys.path.append("/home/xxxxxxxx/env/lib/python3.8/site-packages")
sys.path.append("/home/xxxxxxxx/env/lib/python3.8/site-packages/django")
sys.path.append("/home/xxxxxxxx/mysite/")
def run_with_cgi(application):
environ = dict(os.environ.items())
environ['wsgi.input'] = sys.stdin.buffer
environ['wsgi.errors'] = sys.stderr.buffer
environ['wsgi.version'] = (1,0)
environ['wsgi.multithread'] = False
environ['wsgi.multiprocess'] = True
environ['wsgi.run_once'] = True
environ['PATH_INFO'] = environ.get('PATH_INFO',"/") # 追加
if environ.get('HTTPS','off') in ('on','1'):
environ['wsgi.url_scheme'] = 'https'
else:
environ['wsgi.url_scheme'] = 'http'
headers_set = []
headers_sent = []
def write(data):
if not headers_set:
raise AssertionError("write() before start_response()")
elif not headers_sent:
# Before the first output, send the stored headers
status, response_headers = headers_sent[:] = headers_set
sys.stdout.buffer.write(('Status: %s\r\n' % status).encode("ascii"))
for header in response_headers:
sys.stdout.buffer.write(('%s: %s\r\n' % header).encode("ascii"))
sys.stdout.buffer.write(('\r\n').encode("ascii"))
sys.stdout.buffer.write(data)
sys.stdout.buffer.flush()
def start_response(status,response_headers,exc_info=None):
if exc_info:
try:
if headers_sent:
# Re-raise original exception if headers sent
raise exc_info[0](exc_info[1]).with_traceback(exc_info[2])
finally:
exc_info = None # avoid dangling circular ref
elif headers_set:
raise AssertionError("Headers already set!")
headers_set[:] = [status,response_headers]
return write
result = application(environ, start_response)
try:
for data in result:
if data: # don't send headers until body appears
write(data)
if not headers_sent:
write('') # send headers now if body was empty
finally:
if hasattr(result,'close'):
result.close()
# Change to the name of your settings module
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
from django.core.wsgi import get_wsgi_application
run_with_cgi(get_wsgi_application())
-------
vi .htaccess
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ mysite.cgi/$1 [QSA,L]
chmod 755 mysite.cgi
chmod 604 .htaccess
http://xxxxxxxx.xsrv.jp/top
cd
cd mysite
cd mysite
vi settings.py
ALLOWED_HOSTS = []
ALLOWED_HOSTS = ['*']
http://xxxxxxxx.xsrv.jp/top
http://xxxxxxxx.xsrv.jp/top/admin
7,アプリを追加
cd ../
python manage.py startapp polls
cd polls
vi views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
---
vi urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
cd ../
cd mysite
vi urls.py
from django.conf.urls import include
url(r'^polls/', include('polls.urls', namespace='polls')),
vi settings.py
INSTALLED_APPS = [
'polls',
]
8,AdminのCSSを有効にする
vi settings.py
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
#STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = './static/'
vi urls.py
----
from django.conf import settings
from django.conf.urls.static import static
from django.views.static import serve
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^admin/([a-xA-Z0-9_]*/)*static/(?P<path>.*)$', serve, {'document_root': settings.STATIC_ROOT}),
]
cd ../
python manage.py collectstatic
vi settings.py
LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = 'ja'
関連ページ
//https://kazusa-pg.com/xserver-django/
//https://note.com/coeeff/n/neab8acfde97e
//https://jurasite.com/post-92
//https://liberal-learner.work/it/diet-record/
//https://www.xserver.ne.jp/manual/man_server_ssh.php