0
0

More than 1 year has passed since last update.

Python3でCGIチャレンジ5 簡易ログイン機能

Posted at

作業フォルダ

ps5

作業

html1つとpy1つ作成
image.png

index.htmlの作成

index.html
<html>
<head><meta http-equiv="content-type" charset="UTF-8"></head>
<body>
  <form action="/cgi-bin/authentication.py" method="POST">
    ID:<input type="text" name="ID">
    PASS:<input type="text" name="PASS">
    <input type="submit" value="ログイン">
  </form>
</body>
</html>

cgi-binフォルダの作成

authentication.pyの作成。cgi-bin配下に作成。

authentication.py
import cgi
import cgitb
import csv
cgitb.enable()

print("Content-Type: text/html")
print()   

form = cgi.FieldStorage()
id = form['ID'].value
password = form['PASS'].value

file_name = "password.txt"
fieldnames = ['ID', 'PASS']
try:
  with open(file_name, 'r', encoding='UTF-8', newline="") as f:

    reader = csv.DictReader(f, delimiter=",", quotechar='"')
    for row in reader:
      if row['ID'] == id:
        if row['PASS'] == password:
          print('ログインしました')
          break
        else:
          print('パスワードが間違ってます')
          break
    else:
      d = {'ID': id, 'PASS': password}

      with open(file_name, 'a', encoding='UTF-8', newline="") as f2:
        writer = csv.DictWriter(f2, fieldnames=fieldnames, delimiter=",", quotechar='"')
        writer.writerow(d)
        print('ID登録しました')

except Exception as e:
  print(e)
  with open(file_name, 'w', encoding='UTF-8', newline="") as f:
    writer = csv.DictWriter(f, fieldnames=fieldnames, delimiter=",", quotechar='"')

    # writeheaderでヘッダー出力
    writer.writeheader()

    d = {'ID': id, 'PASS': password}
    writer.writerow(d)
    print('ファイル生成とID登録しました')

ターミナルでコマンド実行して、ローカルでCGIサーバーを起動する。

python -m http.server --cgi 8000

ブラウザで確認

[http://localhost:8000]

結果

index.html
image.png

IDにaaa、PASSに123入れてログイン
開くファイルがなくてエラーになるので、ヘッダーつけてファイルに書き込み
image.png

ファイル生成される
image.png

もう一回ログイン
image.png

違うID/PASS(bbb/111)でログイン
image.png

PASS違い(bbb/222)でログイン
image.png

理解したこと

-ファイルオープンを'r'にしないとreaderが読めない。
-読めないとExceptionになる
-rでファイルオープン中でも、aで同じファイルをオープンできる。
-for文のelse(Python独特な構文)の使い方

0
0
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
0
0