LoginSignup
18
31

More than 5 years have passed since last update.

Pythonの標準ライブラリでさくっとAPIサーバとWebサーバを立ち上げる

Posted at

概要

CORS(Cross-Origin Resource Sharing)について動作確認するのに、Pythonの標準ライブラリを利用してAPIサーバとWebサーバを立ち上げてみました。

GitHubにも今回利用したソースをアップしています。
https://github.com/kai-kou/simple_api_and_web_server_python

実装

Pythonのバージョンは3.6.6で標準ライブラリのみで検証するので、仮想環境やDockerも利用していません。

> python --version
Python 3.6.6

> mkdir 任意のディレクトリ
> cd 任意のディレクトリ
> touch app.py
> touch index.html

APIサーバの実装です。wsgirefを利用しています。ドキュメントに使用例もあって親切です。ありがたや

21.4. wsgiref — WSGI ユーティリティとリファレンス実装
https://docs.python.jp/3/library/wsgiref.html

アクセスするとJSONを返すだけの実装です。
Access-Control-Allow-Origin を指定しないと、ブラウザさんにNo 'Access-Control-Allow-Origin' header is present on the requested resource. って怒られるので注意しましょう(1敗

app.py
from wsgiref.simple_server import make_server

import json


def app(environ, start_response):
  status = '200 OK'
  headers = [
    ('Content-type', 'application/json; charset=utf-8'),
    ('Access-Control-Allow-Origin', '*'),
  ]
  start_response(status, headers)

  return [json.dumps({'message':'hoge'}).encode("utf-8")]

with make_server('', 3000, app) as httpd:
  print("Serving on port 3000...")
  httpd.serve_forever()

APIサーバへアクセスするクライアントの実装です。
XMLHttpRequest を利用してAPIサーバにGETして結果をログ出力しています。

index.html
<html>
  <body>
    <script>
      var req = new XMLHttpRequest();
      req.open('GET', 'http://localhost:3000/');
      req.onreadystatechange = function() {
        if (req.readyState == 4 && req.status == 200) {
          console.log(req.responseText);
        }
      };
      req.send(null);
      </script>
  </body>
</html>

準備ができたので、サーバを立ち上げてブラウザでアクセスしてみます。
APIとWebサーバとで、別々のコンソールが必要になります。

APIサーバの立ち上げ
> python app.py
Serving on port 3000...

Webサーバの立ち上げ
> python -m http.server 8080
Serving HTTP on 0.0.0.0 port 8080 (http://0.0.0.0:8080/) ...

スクリーンショット 2018-10-31 13.23.42.png

はい。
無事に両方立ち上がり、WebサーバからAPIサーバへアクセスできました。

まとめ

API、Web開発するにも、フレームワークを利用する事が多いですが、シンプルな構成で実装すると、問題が起こった際の切り分けに役立つので、便利です。

参考

21.4. wsgiref — WSGI ユーティリティとリファレンス実装
https://docs.python.jp/3/library/wsgiref.html

JavascriptのAjaxについての基本まとめ
https://qiita.com/katsunory/items/9bf9ee49ee5c08bf2b3d

18
31
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
31