Thursday, May 9, 2024

Djangoにmatplotlibで円グラフ表示

Amazon Linux 2023 で再度トライ

sudo yum update

sudo yum install python3-pip

pip install django

python3 -m django --version

pip3 install matplotlib

django-admin startproject mymatplotlibsite

settings.py の ALLOWED_HOSTS = ['34.229.238.162']を編集

python3 manage.py runserver 0.0.0.0:8000 疎通確認

python3 manage.py startapp myfirstplot 

この後、views.py に下記をかいて表示させて確認(チュートリアル1参考)

def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

今回はグラフを表示させたいだけなのでモデルは必要ないと思うがmodels.pyをチュートリアルと同じように作成(使わない前提)

アプリケーションをプロジェクトに含める(settings.py)

INSTALLED_APPS = [
    'myfirstplot.apps.MyfirstplotConfig',

python3 manage.py makemigrations myfirstplot
python3 manage.py sqlmigrate myfirstplot 0001
python3 manage.py migrate

モデルクラスにクラスメソッドを追加

adminサイトにログインできるユーザーを作成

python3 manage.py createsuperuser

myfirstplot/admin.py を編集

Wednesday, May 8, 2024

djangoproject.com のチュートリアル

djangoproject.com のチュートリアル(日本語が選べれるのが素晴らしい)

先日作ったEC2インスタンス上でvenv をもう一度(混乱したため。。。

mkdir ~/myprojectdir2

cd ~/myprojectdir2

python3 -m venv myprojectenv

source myprojectenv/bin/activate

pip install django gunicorn psycopg2-binary

django-admin startproject mysite ~/myprojectdir2

settings.py にALLOWED_HOSTS = ['35.175.86.54']

ここからチュートリアル

~/myprojectdir2/manage.py runserver 0.0.0.0:8000 << 立ち上がるがmigrateしろと怒られる

python manage.py startapp polls

下記のファイルにチュートリアルに従って編集・追加
polls/views.py
polls/urls.py
mysite/urls.py

python manage.py migrate

mysite/settings.py編集

python manage.py makemigrations polls

python manage.py sqlmigrate polls 0001

python manage.py migrate

python manage.py createsuperuser

polls/admin.py 編集





Part2 まで完了。EC2上でアプリが動いてます!

次の日 part 3 完了。下記のリンクにテンプレートのことが詳しく:
https://docs.djangoproject.com/ja/5.0/topics/templates/

Monday, May 6, 2024

Django + venv on Amazon Linux 2023

 Digital Ocean のチュートリアルがうまく動かないので Amazon Linux 2023 で再度トライ


sudo yum update

sudo yum install python3-pip

sudo pip3 install virtualenv

virtualenv your_project_name

source your_project_name/bin/activate

deactivate

ここからDitalOceanの続きをしようとpip install django gunicorn psycopg2-binaryしたがすでにある?

DitalOceanの"myprojectdir"が"myproject"

Step4から

django-admin startproject mysurvey ~/myproject

DitalOceanの"myproject"が"mysurvey"

~/myproject/manage.py makemigrations

~/myproject/manage.py migrate


~/myproject/manage.py createsuperuser

~/myproject/manage.py collectstatic

sudo ufw allow 8000 << 通らなかったが今回は無視

~/myproject/manage.py runserver 0.0.0.0:8000

インスタンスに穴をあける



開通!



Monday, April 22, 2024

EC2上にDockerをインストール(続き)

 先日の続き【Docker講座5】と【Docker講座6】の途中までだった。。。(

https://blog.shiro.net/2024/02/ec2docker.html

CloudTech というYouTubeチャンネルのDocker講座【Docker講座7】から

https://www.youtube.com/@cloudtech9882

こちらの方のチュートリアルから

git clone https://github.com/AWSCLOUDTECH/tutorial.git


■コマンドメモ docker run -it --rm myimage1



Test stage FROM alpine:3.13.5 AS test LABEL application=todobackend Install basic utilities RUN apk add --no-cache bash git ■コマンドメモ sudo systemctl status docker.service sudo systemctl start docker.service docker build -t myimage1 . << Docker イメージを作成 docker images << イメージの確認 docker history myimage1 RUN apk add --no-cache curl docker build -t myimage2 . docker inspect xxxxxx docker rmi -f xxxxxx docker images -q docker rmi -f `docker images -q` Create app user RUN addgroup -g 1000 app && \ adduser -u 1000 -G app -D app Copy and install application source and pre-built dependencies COPY --from=test --chown=app:app /build /build COPY --from=test --chown=app:app /app /app RUN pip3 install -r /build/requirements.txt -f /build --no-index --no-cache-dir RUN rm -rf /build Set working directory and application user WORKDIR /app USER app ■ビルド docker build -t todobackend-release . ■アプリケーション実行 docker run -it --rm -p 8000:8000 todobackend-release uwsgi --http=0.0.0.0:8000 --module=todobackend.wsgi --master


一応、Dockerイメージが立ち上がって、そこにインストールされているAppが動いた。が、、、いまいち理解していない。。。




Monday, March 4, 2024

Mongo DB

 Mongo DB

デモが Ubuntu だったので今回はEC2でUbuntuを選択してインスタンス起動

アップデートして

ubuntu@ip-172-31-20-57:~$ sudo apt update

Ubuntu は初めてなのでバージョンチェック

ubuntu@ip-172-31-20-57:~$ cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=22.04
DISTRIB_CODENAME=jammy
DISTRIB_DESCRIPTION="Ubuntu 22.04.3 LTS"

下記のサイト(参照)のインストラクションをフォローして(オプションは全てスキップ)、ミニマム環境で mongosh を起動できたのインストールはできているみたい:

サンプルプログラム:
import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

mydict = {"name" : "Hilda", "address" : "Highway 37"}

x = mycol.insert_one(mydict)

print(mydb.list_collection_names())

サンプルプログラムを走らせようとしたら no module found がでたので



sudo apt-get install pip

sudo pip install pymongo

pymongo をインストールしたらサンプルプログラムが走りましたのでインストールはできたみたい。






Monday, February 26, 2024

Python 練習

 

Shopping Cart Module

Functional Requirements

You are to prototype business logic for an online shopping cart. Eventually, the user will enter information into an HTML form and hit "Submit". This will trigger Python logic processing the order. The results of the order will be converted to JSON for storage in a NoSQL database. 

For this current assignment, you can ignore the presentation layer (the HTML form). Instead, prototype the logic by letting the user (who will be a tester on your team), respond to command line prompts and enter data like "product id", "product name", "price", "customer id", etc. Use at least four data fields - more if you are feeling ambitious!

Likewise, ignore the part of the data layer that involves implementing the actual NoSQL database. For now, use .json files as your data storage mechanism. When you create the .json files, be sure to use some key field like order_number in the file name so you can retrieve each order from your file system. To finish the project, write a some code to search for orders by order number, read the JSON from the selected file, and present complete information from the order on the Python command line. 

ユーザー入力DataをJSON 形式で保存・追加:

import os
import json
input_id = input("Enter order #: ")
input_product_no = input("Enter product #: ")
input_productname = input("Enter product name: ")
input_price = input("Enter price: ")
with open('store_jsonfile.json',
    mode="r",
    encoding="utf-8") as file:
    orders = json.load(file)
    #print(orders)
    orders[input_id] = {"product_sku": input_product_no, "productname": input_productname, "price": input_price}
    #print(orders)
with open('store_jsonfile.json',
    mode="w",
    encoding="utf-8") as file:
    json.dump(orders, file, indent=4)

検索して表示:

import os
import json
input_id = input("Enter order #: ")
with open('store_jsonfile.json', mode="r", encoding="utf-8") as file:
    orders = json.load(file)
    
    order = orders[input_id]
    print("Order #: ", input_id)
    print("Product SKU: ", order['product_sku']) 
    print("Product Name: ", order['productname'])
    print("Price: ", order['price'])


Sunday, February 25, 2024

Python Collection

 Python Collection

Python CollectionsOrdered/IndexedChangeableAllows Duplicates
Setnono(追加・削除は可能)no
Tupleyesnoyes
Dictionaryyesyesno
Listyesyesyes

Sets

Python sets are unchangeable and unordered. They do not allow duplicates. (See the chart below to see how sets compare to other collections).

What the term "unchangeable" means in the context of Python sets is that the elements themselves cannot be changeable.  The string "blue" cannot be changed. Variations like "Blue", or "bleu", or "skyblue" are just different strings, not changes to "blue". So you can make sets out of unchangeable data types like strings, integers, and booleans. 


Tuples

Tuples really are unchangeable. There are no tuple.add() or tuble.remove() methods. If you want to change a tuple, you will need a hack that migrates the tuple into something changeable and then migrates back to the tuple with new and improved membership:


Dictionaries

Python  dictionaries work very well with JSON. Consider the two code samples below. Which is Python? Which is JSON?


Lists

Lists are the closest feature Python has to what other languages call arrays. You can declare a Python list like this: