flask入門3

sqlite3

create table results (
	id integer primary key autoincrement,
	title text,
	data text,
	img text,
	created datetime
);

models.py

def select(con, pk):
	cur = con.execute('select id, title, data, img, created from results where id=?', (pk,))
	return cur.fetchone()

def select_all(con):
	cur = con.execute('select id, title, data, img, created from results order by id desc')
	return cur.fetchall()

def delete(con, pk):
	cur = con.cursor()
	cur.execute('delete from results where id=?', (pk,))
	con.commit()

run.py

@app.route('/')
def index():
	con = get_db()
	results = models.select_all(con)
	return render_template('index.html', results=results)

@app.route('/delete/<pk>')
def delete(pk):
	con = get_db()
	models.delete(con, pk)
	return redirect(url_for('index'))

@app.route('/view/<pk>')
def view(pk):
	con = get_db()
	result = models.select(con, pk)
	return render_template("view.html", result=result)

index.html

    {% for result in results %}
    <tr>
        <td>{{result.id}}</td>
        <td>{{result.title|safe}}</td>
        <td>{{result.rcreated}}</td>
        <td>
            <a href="/view/{{result.id}}"><button class="btn btn-primary">参照</button></a>
            <form action="/delete/{{result.id}}" style="display:inline" method="post">
                <input class="btn btn-danger" type="submit" value="削除" onclick='return confirm("削除しますがよろしいですか")';>
            </form>
        </td>
    </tr>
    {% endfor %}

view.html

{% extends "base.html" %}
{% block body %}
<h1>結果参照</h1>

<h3>{{ result.id}}: {{ result.title|safe}}</h3>
<p>{{ result.created }}</p>
<div class="row">
	<img src="{{ url_for('static', filename=result.img)}}">
</div>

<div class="row">
	<textarea class="form-control" name="data" rows="5">{{result.data}}</textarea>
</div>
<br><br>
{% endblock %}

OK 一通り理解した
mysql & Dockerでやりたい

flask入門2

app.py

from flask import Flask
from flask import Flask, redirect, url_for, render_template

app = Flask(__name__)
app.config.update(dict(
	DATABASE = os.path.join(app.root_path, 'db.sqlite3'),
	SECRET_KEY='foo-baa',
))

@app.route('/')
def index():
	return render_template('index.html', result{})

@app.route('/create')
def create():
	return render_template('edit.html')

@app.route('/analysis', methods=['POST'])
def analysis():
	return redirect(url_for('view', pk=0))

@app.route('/delete/<pk>')
def delete(pk)
	return redirect(url_for('index'))

@app.route('/view/<pk>')
def view(pk):
	return render_template("index.html", values=values)

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

base.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>簡易分析ツール</title>
	<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
            integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
            crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
            integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
            crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
            integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
            crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
          integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" type=text/css href="{{ url_for('static', filename='style.css') }}">
</head>
<body>

<header>
	<div class="navbar navbar-dark bg-dark box-shadow">
        <div class="container d-flex justify-content-between">
            <a href="/" class="navbar-brand d-flex align-items-center">
                <strong>簡易分析ツール</strong>
            </a>
        </div>
    </div>
</header>

<div class="container">
	{% block body %}
	{% endblock %}
</div>
</body>
</html>

edit.html

{% extends "base.html" %}
{% block body %}
<h1>新規分析</h1>
<form action="{{ url_for('analysis') }}">
	<label>タイトル</label>
	<input class="form-control" type="text" size="30" name="title">
	<label>分析データ</label>
	<textarea class="form-control" name="data" rows="5"></textarea>
	<input class="btn btn-primary" type="submit" value="送信">
</form>
{% endblock %}

view.html

{% extends "base.html" %}
{% block body %}
<h1>結果参照</h1>

<h3>0:サンプルタイトル</h3>
<p>2022/01/01 12:00</p>
<div class="row">
	ここにグラフを配置
</div>

<div class="row">
	<textarea class="form-control" name="data" rows="5">テストデータ</textarea>
</div>
<br><br>
{% endblock %}

http://192.168.33.10:8000/

ほう、これは凄い
Djangoに似てる

ubuntu20.04にapache2とMod_wsgi

$ Mod_wsgi on
$ sudo apt install apache2 apache2-utils ssl-cert libapache2-mod-wsgi
$ sudo systemctl restart apache2
$ sudo mkdir -p /var/www/scripts
$ sudo vi /var/www/scripts/test_wsgi_script.py

def application(environ, start_response):
	status = '200 ok'
	html = '<html>\n' \
			'<body>\n' \
			'hello, mod_wsgi is working\n' \
			'</body>\n' \
			'</html>\n'
	response_header = [('Content-type', 'text/html')]
	start_response(status, response_header)
	return

$ sudo vi /etc/apache2/conf-available/mod-wsgi.conf

WSGIScriptAlias /test_wsgi /var/www/scripts/test_wsgi_script.py

$ sudo a2enconf mod-wsgi
$ sudo systemctl restart apache2
http://192.168.33.10/test_wsgi

flask入門

$ flask –version
Python 3.8.10
Flask 2.0.2
Werkzeug 2.0.2

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
	return '<html><body><h1>sample</h1></body></html>'

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

template/index.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
	<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
            integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
            crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
            integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
            crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
            integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
            crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
          integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" type=text/css href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
	<header>
		<div class="navbar navbar-dark bg-dark box-shadow">
            <div class="container d-flex justify-content-between">
                <a href="/" class="navbar-brand d-flex align-items-center">
                    <strong>サンプル</strong>
                </a>
            </div>
        </div>
	</header>
	<div class="content container">
		<h2>値の表示</h2>
        <p>値1:{{ values.val1 }}</p>
        <p>値2:{{ values.val2 }}</p>
	</div>
</body>
</html>

app.py

from flask import Flask
from flask import render_template

app = Flask(__name__)

@app.route('/')
def hello_world():
	values = {"val1": 100, "val2": 200}
	return render_template("index.html", values=values)

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

[Rust] Basic 1: variable and array

### variables

fn main() {
    let x = 13;
    println!("{}", x);

    let x: f64 = 3.14159;
    println!("{}", x);

    let x;
    x = 0;
    println!("{}", x);
}

$ target/debug/hello
13
3.14159
0

variables are modifiable.
mutable: compiler allows read and write
immutable: the compiler will only allow the variable to be read from
mutable values are denoted with a mut keyword.

fn main() {
    let mut x = 42;
    println!("{}", x);
    x = 13;
    println!("{}", x);
}

booleans: bool
unsigned integers(符号なし): u8, u16, u32, u64, u128
signed integers(符号あり): i8, i16, i32, i64, i128
pointer sized integers: usize, isize
floating point: f32, f64
tuple: (value, value, …)
arrays:
slices,
str
Numeric types can be explicitly specified by appending the type to the end of the number.(13u32, 2u8)

fn main() {
    let x = 12;
    let a = 12u8;
    let b = 4.3;
    let c = 4.3f32;
    let bv = true;
    let t = (13, false);
    let sentence = "hello world";
    println!(
    	"{} {} {} {} {} {} {} {}",
    	x, a, b, c, bv, t.0, t.1, sentence
    )
}

$ target/debug/hello
12 12 4.3 4.3 true 13 false hello world

### Basic Type Conversion
as で変換する

fn main() {
    let a = 13u8;
    let b = 7u32;
    let c = a as u32 + b;
    println!("{}", c);

    let t = true;
    println!("{}", t as u8);
}

$ target/debug/hello
20
1

### constants
constant used many times efficiently.
constant must always have explicit types.
constant names are always in SCREAMING_SNAKE_CASE.

const PI: f32 = 3.14159;

fn main() {
    println!(
    	"to make an apple {} from scratch, you must first create a universe.",
    	PI
    )
}

const PI: u8 = 12; とも書く

### Arrays
an array is a fixed length collection of data.
data type for an array is [T;N] where T is the elements type and N is the fixed length.
Individual elements can be retrieved with the x operator

fn main() {
    let nums: [i32; 3] = [1, 2, 3];
    println!("{:?}", nums);
    println!("{}", nums[1]);
}

$ target/debug/hello
[1, 2, 3]
2

なるほど

Ubuntu20.04 でRustの環境構築

$ curl –proto ‘=https’ –tlsv1.2 -sSf https://sh.rustup.rs | sh
$ sudo apt install cargo
$ cargo new –bin hello
$ cd hello
$ cargo build
Compiling hello v0.1.0 (/home/vagrant/dev/rust/hello)
Finished dev [unoptimized + debuginfo] target(s) in 0.32s
$ tree
.
├── Cargo.lock
├── Cargo.toml
├── src
│   └── main.rs
└── target
├── CACHEDIR.TAG
└── debug
├── build
├── deps
│   ├── hello-2ab4b0e0c3958f3e
│   └── hello-2ab4b0e0c3958f3e.d
├── examples
├── hello
├── hello.d
└── incremental

7 directories, 8 files

$ target/debug/hello
Hello, world!

ファイルの中身を見てみる
hello/src/main.rs

fn main() {
    println!("Hello, world!");
}

中身をtour of rustと同じにする

fn main() {
    println!("Hello, 🦀");
}

$ cargo build
$ target/debug/hello
Hello, 🦀

なるほど…

Solanaとは?

Solanaは他のブロックチェーンより圧倒的に高速低コスト
ティッカーシンボル: SOL
レイヤー1のみで完結できる
他のブロックチェーンと相互運用ができる(Warmholeというイーサリアムとのブリッジ機能)
長期保有によるステーキング報酬を得られる

トランザクション処理:50,000/秒
トランザクション手数料: 0.00005ドル
ブロック生成速度: 0.4秒

Serumでエアドロップ、solanaでテザーがローンチ、NFTプロジェクト立ち上げ(猿の画像を買うのにSOLが必要) などで高騰

PoH(proof of history): timestampで証明
ステーキングとは一時的にロックさせる
インターオペラビリティ
Audius, Serum, LoanSnap, USDT, USDCと連携

https://solana.com/

solanaのblock chain engineerのjob opportunity
– Proficiency with systems level languages like Rust, C, C++
– Experience with smart contract development, distributed computing, and/or system design
– Exceptional quantitative and analytical skills – bonus if you’ve applied those to trading strategies in a professional capacity
– Belief in the benefits of open source contribution
– Passion for software development, DeFi, and cryptocurrencies

なるほどー、 solana作ってる奴らは皆んなRustやってるのか…

[Ethereum] SolidityのContractをweb3.jsで呼び出したい

<body>
  <script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js/dist/web3.min.js"></script>
	<script>
    const web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/v3/*"));
      const address = "*";
      const abi = [{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"clients","outputs":[{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"gender","type":"string"},{"internalType":"uint256","name":"weight","type":"uint256"},{"internalType":"uint256","name":"height","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"string","name":"_name","type":"string"},{"internalType":"string","name":"_gender","type":"string"},{"internalType":"uint256","name":"_weight","type":"uint256"},{"internalType":"uint256","name":"_height","type":"uint256"}],"name":"register","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"excesise","outputs":[{"internalType":"uint256","name":"newWeight","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}]

      const contract = new web3.eth.Contract(abi, address);
      const handleCall = async () => {
        await contract.methods.register("tanaka", "aaa", 65, 175);
        const result = await contract.methods.excesise.call();
        console.log(result);
      };
      handleCall();
      
    </script>
</body>
</html>

{arguments: Array(0), call: ƒ, send: ƒ, encodeABI: ƒ, estimateGas: ƒ, …}

何故だろう… 期待通りにいかん…

[ethereum] solidityをRopstenにデプロイしたい

$ npm install truffle-hdwallet-provider
$ truffle compile

truffleconfig.js

const HDWalletProvider = require("truffle-hdwallet-provider");
const mnemonic = "";

    ropsten: {
      provider: () => new HDWalletProvider(mnemonic, `https://ropsten.infura.io/v3/${project_id}`),
      network_id: 3,       // Ropsten's id
      gas: 5500000,        // Ropsten has a lower block limit than mainnet
      confirmations: 2,    // # of confs to wait between deployments. (default: 0)
      timeoutBlocks: 200,  // # of blocks before a deployment times out  (minimum/default: 50)
      skipDryRun: true     // Skip dry run before migrations? (default: false for public nets )
    },

$ truffle migrate –network ropsten

なるほど、これは凄い