【Python】classの__init__の使い方

pythonでの関数の呼び出し

def some_function(something):
	print(something)

some_function("hello world")

Classにした場合
L インスタンスを生成して処理を実行する
  L クラスの中の関数をメソッドと呼ぶ

class SomeClass:
	def __init__(self, something):
		self.something = something

	def some_function(self):
		print(self.something)


c = SomeClass("hello world")
c.some_function()
class SomeClass:
	def __init__(self, something):
		self.something = something

	def some_function(self):
		print(self.something)

	def some_function2(self):
		return self.something


c = SomeClass("hello world")
c.some_function()
print(c.some_function2())

selfはインスタンス自身のこと
initはデータの初期化の関数

class MyStatus:
	def __init__(self, age, name, height, weight):
		self.age = age
		self.name = name
		self.height = height
		self.weight = weight

	def print_name(self):
		print(self.name)

	def print_age(self):
		print(self.age)

	def print_height(self):
		print(self.height)

	def print_weight(self):
		print(self.weight)

a = MyStatus(14, "yamada", 160, 55)
a.print_height()	 

コーヒーメーカーのClassを作ってみる

class CoffeeMaker:
	def __init__(self, water, brand, tempreture):
		self.water = water # mill
		self.brand = brand
		self.tempreture = tempreture

	def boiling(self):
		boilingTime = self.water / 10 * self.tempreture
		print(boilingTime)

	def brew(self):
		print(self.brand + "を滴れました")

a = CoffeeMaker(300, "brend", 3)
a.boiling()	
a.brew() 

$ python3 test.py
90.0
brendを滴れました

なるほど、Classと関数とinitの使い方について、自分で例を作ると構造を理解できますね。

phpの場合はinitのところが__contructになります。引数はconstructで定義しています。

class Dog {
private $name;

public function __construct($name) {
$this->name = $name;
}

public function getName(){
echo $this->name;
}
}

$dog = new Dog(“Pochi”);

$dog->getName();
[/code]

ini_set('display_errors', "On");

class CoffeeShop {
	private $order;
	private $pay;

	public function __construct($order, $pay) {
		$this->order = $order;
		$this->pay = $pay;
	}

	public function coffeePrice(){
		switch ($this->order) {
			case "ブレンド":
				echo "price is 330 yen\n";
				$price = 330;
				break;
			case "アメリカン":
				echo "price is 350 yen\n";
				$price = 350;
				break;
			case "アイスコーヒー":
				echo "price is 380 yen\n";
				$price = 380;
				break;
			default:
				echo "not available at this store";
		}

		$change = $this->pay - $price;
		return $change;
	}

	
}

$a = new CoffeeShop("ブレンド", 1000);
$b = $a->coffeePrice();
echo $b;

【python】sha256

Pythonのハッシュ値を求める関数はhashlibにある

import hashlib

x = 'abc'

m = hashlib.md5(x.encode()).hexdigest()
sha256 = hashlib.sha256(x.encode()).hexdigest()
sha384 = hashlib.sha384(x.encode()).hexdigest()
sha512 = hashlib.sha512(x.encode()).hexdigest()


print(m)
print(sha256)
print(sha384)
print(sha512)

encodeはコードの符号化
hexdigest は16進数文字列に変換

$ python3 test.py
900150983cd24fb0d6963f7d28e17f72
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7
ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f

マークルツリーとは

マークルツリーとは?
L 二つのトランザクションのハッシュ値二つを合わせたデータに対してハッシュ値を計算するという操作を繰り返して完成するハッシュ値のツリー構造
一番上のハッシュ値はマークルルートと呼ぶ
ハッシュ値を持つことにより、すべてのトランザクションを保存しなくて済む
ブロックヘッダーのみをwalletは保持する

【sakura vps】alma linuxにgitを入れる

ssh後にgitを確認
$ git –version
-bash: git: command not found

gitが入っていないのでgitを入れる
$ sudo dnf -y install git
Failed to set locale, defaulting to C.UTF-8
Killed

killedとなっているので、logを確認
$ sudo cat /var/log/messages
メモリが足りないっぽいのでswapを追加
$ sudo mkdir /var/swap
$ sudo dd if=/dev/zero of=/var/swap/swap0 bs=1M count=4096
$ sudo chmod 0600 /var/swap/swap0
$ sudo mkswap /var/swap/swap0
$ swapon /var/swap/swap0
$ free
total used free shared buff/cache available
Mem: 469712 94524 143384 15428 231804 336236
Swap: 4194300 40960 4153340

再度git をインストール
$ sudo dnf -y install git
$ git -v
git version 2.39.3

【Python】RC4の実装

def KSA(key):
	S = list(range(256))
	j = 0
	for i in range(256):
		j = (j + S[i] + ord(key[i % len(key)])) % 256
		S[i], S[j] = S[j], S[i]
	return S

def PRGA(S):
	i,j = 0, 0
	while True:
		i = (i + 1) % 256
		j = (j + S[i]) % 256
		S[i], S[j] = S[j], S[i]
		K = S[(S[i] + S[j]) % 256]
		yield K

def RC4(data, key):
	S = KSA(key)
	gen = PRGA(S)
	data = bytearray(data, encoding='utf-8')
	result = bytearray(c ^ n for c, n in zip(data, gen))
	return str(result)

key = 'this_is_a_key'
message = 'this_is_a_message'

chiphertext = RC4(message, key)
print(chiphertext)

これでもいける

from Crypto.Cipher import ARC4
key = b'Very long and confidential key'
cipher = ARC4.new(key)
msg = cipher.encrypt(b'Open the pod bay doors, HAL')
print(msg)

【Python】DESを実装する

$ pip3 install base32hex

import base32hex
import hashlib
from Crypto.Cipher import DES
from Crypto.Random import get_random_bytes

password = "Password"
salt = '\x28\xAB\xBC\xCD\xDE\xEF\x00\x33'
key = password + salt
m = hashlib.md5(key)
key = m.digest()
(dk, iv) = (key[:8], key[8:])
crypter = DES.new(dk, DES.MODE_CBC, iv)

plain_text = "hello world"

print("The plain text is:", plain_text)
plain_text += '\x00' * (8 - len(plainn_text) % 8)
ciphertext = crypter.encrypt(plain_text)
encode_string = base32hex.b32encode(ciphertext)
print("the encoded string is : ", encode_string)

Traceback (most recent call last):
File “aes.py”, line 9, in
m = hashlib.md5(key)
TypeError: Unicode-objects must be encoded before hashing

pyDesを使用します。
$ pip3 install pyDes
https://github.com/twhiteman/pyDes

from pyDes import *

data = "Please encrypt my data"
k = des("DESCRYPT", CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5)
d = k.encrypt(data)
print(d)
print(k.decrypt(d))

b’o\xceSef\xe6\xa6\x8f\x82\x98\xc7V\xd0I\xdc\x03\x1e\x97\xe4\x99&\x07\x9cI’
b’Please encrypt my data’

【Python】AESを実装しよう

pycryptodomeをインストールします
$ pip3 install pycryptodome

from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util import Padding
from hashlib import pbkdf2_hmac

targetText = "hello world"

salt = get_random_bytes(16)
iv = get_random_bytes(16)

passPhrase = "password123"

key = pbkdf2_hmac('sha256', bytes(passPhrase, encoding='utf-8'), salt, 50000, int(128/8))

aes = AES.new(key, AES.MODE_CBC, iv)
data = Padding.pad(targetText.encode('utf-8'), AES.block_size, 'pkcs7')
encrypted = aes.encrypt(data)
print(encrypted)

$ python3 aes.py
b’\x86\xb4V\x7f\xfaN\x83\xc9\x87\x02\xd1\x15z\x19bU’

flaskでcssを使いたい

cssファイルはtemplatesフォルダ配下には作らない
↓これはダメ
$ tree
.
├── app.py
└── templates
├── css
│   └── style.css
└── index.html

staticというフォルダを作り、その中にcssファイルを入れる
$ tree
.
├── app.py
├── static
│   └── style.css
└── templates
└── index.html

templateからは以下で読み込む

	<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}" type="text/css">

flask JSONを返却する

jsonifyを使用する

from flask import Flask, render_template, request, jsonify

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
app.config['JSON_SORT_KEYS'] = False

@app.route('/hello')
def hello():
	data = [
		{"name": "山田"},
		{"age": 30}
	]
	return jsonify({
			'status' : 'OK',
			'data' : data
		})

if __name__ == "__main__":
	app.run(debug=True, host='192.168.56.10', port=8000)