AI×医療事務(カナダ)

今は医療事務しているので医療事務関連、IT関連をのんびりと備忘録も含め記載していきます カナダ・歯科助手のことも復習がてら記載中 

FlaskとMySQLでToDoアプリ 2021.5/24

FlaskとMySQLでToDoアプリを実装しよう

#mysql.server start

 

mysql -u root -p

↓ パスワード入力しエンター

Enter password:

Welcome to the MySQL monitor.  Commands end with ; or \g.

Your MySQL connection id is 21

Server version: 8.0.23 Homebrew

 

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

 

Oracle is a registered trademark of Oracle Corporation and/or its

affiliates. Other names may be trademarks of their respective

owners.

 

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

 

mysql>

 

#もうあるので飛ばす

 todo_appというデータベースとtodoというテーブルを作成

todo_appデータベースを作成<mysql シェル?内>

mysql>  create database todo_app;

mysql> create database todo_app;

Query OK, 1 row affected (0.00 sec)

 

 

  

todo_appデータベースを使用するためにuseコマンド

use todo_app;

Database changed

 (Reading table information for completion of table and column names

You can turn off this feature to get a quicker startup with -A

 

Database changed)

 

todoテーブルを作成

mysql> create table todo(
task_id INT(10) primary key NOT NULL AUTO_INCREMENT,
task_content VARCHAR(200) NOT NULL,
done_flag INT(10) DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

Query OK, 0 rows affected, 2 warnings (0.03 sec)

 
 (すでにある場合:ERROR 1050 (42S01): Table 'todo' already exists
作成したカラムは、
task_id
task_content(todoの内容)
done_flag(完了したタスク⇢1 未完了⇢0が入る)
created_at(タスクを追加した時間)
の4つ
 

PythonMySQLでデータベースと接続

 

テキストエディタにて 「db.py」というタイトルをつけ該当ディレクトリに保存

↓中身

import MySQLdb

def conn_f():
con = MySQLdb.connect(
user="自分の username",
passwd="自分のpassword",
host="localhost",
db="todo_app",
charset="utf8"
)
# cursor = con.cursor() # カーソルの取得
return con

# Debug
if conn_f():
print("接続成功")
else:
print("接続失敗")

 

mysqlからexitする

mysql> exit

Bye

 

python db.py

↓   

接続成功

 

『接続成功』と出力されればdb.pyのコードを下記に変更

import MySQLdb

def conn_f():
con = MySQLdb.connect(
user="root",
passwd="password",
host="localhost",
db="todo_app",
charset="utf8"
)
return con

 

f:id:chocolate22554:20210419155556p:plain

 

 

htmlファイルの作成

 

db.pyと同じフォルダに、templatesフォルダを作成

index.htmlを作成

f:id:chocolate22554:20210524180919p:plain

下記コード↓

<head>
<meta charset="UTF-8">
</head>

<!DOCTYPE html>
<html lang="ja">
<head>
<title>ToDoアプリケーション</title>
<style>
#main {
width: 60%;
border: solid 1px #ccc;
margin: 0 auto;
text-align: center;
}
form , h1, p{
margin: 0 auto;
text-align: center;
}
hr {
width: 50%;
}
</style>
</head>
<body>

<div id="main">
<form method="POST">
<input type="text" name="content" size="35" placeholder="17:00までに牛乳を1本買う"><br>
<input type="submit" value="追加">
</form>

<h1>TODO</h1>
<hr>
<h1>完了したTODO</h1>
</div>
</body>
</html>

 

f:id:chocolate22554:20210419162728p:plain

  • <head>
  •   <meta charset="UTF-8">
  • </head>

入れないと文字化けする

 

 

ブラウザで表示

f:id:chocolate22554:20210524181510p:plain

 

タスクの追加

main.pyを作成

f:id:chocolate22554:20210524181651p:plain

コード↓

# 1.必要なモジュールの読み込み
from flask import Flask, request,redirect, url_for, Response,render_template
from db import conn_f
from datetime import datetime as dt

date = dt.now().strftime('%Y:%m:%d %H:%I:%S')

# 2. Flaskを使うためのおまじない
app = Flask(__name__)

# 3.taskテーブルから完了していないtaskを取得する関数
def get_all_tasks():
conn = conn_f()
cursor = conn.cursor()
# user_idを使う場合(今回はこのsqlは実行しません)
# sql = 'select task_id,task_content,done_flag,created_at from todo where user_id= {0};'.format(user_id)
sql = 'select task_id,task_content,done_flag,created_at from todo where done_flag = 0;'
cursor.execute(sql)
tasks = cursor.fetchall()

cursor.close()
conn.close()
return tasks

# 4.taskテーブルから完了しているtaskを取得する関数
def get_all_done_tasks():
conn = conn_f()
cursor = conn.cursor()
# user_idを使う場合(今回はこのsqlは実行しません)
# sql = 'select task_id,task_content,done_flag,created_at from todo where user_id= {0};'.format(user_id)
sql = 'select task_id,task_content,done_flag,created_at from todo where done_flag = 1;'
cursor.execute(sql)
tasks = cursor.fetchall()

cursor.close()
conn.close()
return tasks

# 5. /にアクセスした時に実行されるindex関数
@app.route('/', methods=['GET'])
def index():
tasks = get_all_tasks()
done_tasks = get_all_done_tasks()
# index.htmlにはリストを渡す
return render_template('index.html', tasks=list(tasks), done_tasks=list(done_tasks))

# 6. TODO(タスク)の追加処理
@app.route('/', methods=['GET','POST'])
def add():
conn = conn_f()
cursor = conn.cursor()
sql = 'insert into todo(task_content,done_flag,created_at) values("{0}", {1}, "{2}");'.format(
request.form['content'],
0,
date)
cursor.execute(sql)
conn.commit()

# 接続を閉じる
cursor.close()
conn.close()

# index.htmlにはリストを渡す
tasks = get_all_tasks()
done_tasks = get_all_done_tasks()
# index.htmlにはリストを渡す
return render_template('index.html', tasks=list(tasks), done_tasks=list(done_tasks))

if __name__ == '__main__':
app.run( port=8000)

 

 

index.htmlを修正

赤枠部分を削除

f:id:chocolate22554:20210524182614p:plain

下記コードを追加

 

<div id="main">
<form method="POST">
<input type="text" name="content" size="35" placeholder="17:00までに牛乳を1本買う"><br>
<input type="submit" value="追加">
</form>

<h1>TODO</h1>

{% for task in tasks %}
<form method="post" action="/update">
<input type="text" name="content" value="{{ task[1] }}">
<input type="hidden" name="task_id" value="{{ task[0] }}">
<input type="submit" value="更新" class="btn">
</form>

<form method="post" action="done">
<input type="hidden" name="task_id" value="{{ task[0] }}">
<input type="submit" value="完了" class="btn">
</form>
<hr>

{% endfor %}
</div>

 

 

python main.py       を実行

* Serving Flask app "main" (lazy loading)

* Environment: production

   WARNING: This is a development server. Do not use it in a production deployment.

   Use a production WSGI server instead.

* Debug mode: off

* Running on http://127.0.0.1:8000/ (Press CTRL+C to quit)

127.0.0.1 - - [24/May/2021 19:02:24] "GET / HTTP/1.1" 200 -

 

ブラウザでhttp://127.0.0.1:8000/にアクセス

 

f:id:chocolate22554:20210524190613p:plain

TODO(タスク)の追加処理

 

main.py

return render_template('index.html', tasks=list(tasks), done_tasks=list(done_tasks))

 

の下に下記を追加

 

@app.route('/done', methods=['POST'])
def done():
conn = conn_f()
cursor = conn.cursor()
sql = 'UPDATE todo SET done_flag=1 where task_id={0};'.format(
request.form['task_id'])
cursor.execute(sql)
conn.commit()
cursor.close()
conn.close()

# indexにリダイレクト
return redirect(url_for('index'))

f:id:chocolate22554:20210524191210p:plain

 

 

index.html

{% endfor %}の下に下記コード追加

 

<h1>完了したTODO</h1>

{% for task in done_tasks %}
<p>{{ task[1] }}</p>
{% endfor %}

f:id:chocolate22554:20210524191629p:plain

 

タスクの更新

main.pyにupdateの部分を追加

 

  # indexにリダイレクト  return redirect(url_for('index'))の下に

f:id:chocolate22554:20210524192047p:plain

下記コードを追加

@app.route('/update', methods=['POST'])
def update():
conn = conn_f()
cursor = conn.cursor()
sql = 'UPDATE todo SET task_content="{0}" where task_id={1};'.format(
request.form['content'],
request.form['task_id'])
cursor.execute(sql)
conn.commit()
cursor.close()
conn.close()
tasks = get_all_tasks()
done_tasks = get_all_done_tasks()
# index.htmlにはリストを渡す
return render_template('index.html', tasks=list(tasks), done_tasks=list(done_tasks))

 

ブラウザには完了したTODOが付け加えられていた

f:id:chocolate22554:20210524192226p:plain

f:id:chocolate22554:20210524192300p:plain

 

========================

===↓経過過程ありのver=======

 

MySQL環境構築

◎Homebrewがインストールされているか?

brew --version

Homebrew 3.1.5

Homebrew/homebrew-core (git revision 8cc1224865; last commit 2021-05-10)

Homebrew/homebrew-cask (git revision 75f162f7e6; last commit 2021-05-10)

 

実行

brew update
brew tap homebrew/versions
brew info mysql
brew install mysql

To restore the stashed changes to /usr/local/Homebrew/Library/Taps/homebrew/homebrew-services, run:

  cd /usr/local/Homebrew/Library/Taps/homebrew/homebrew-services && git stash pop

Updated 4 taps (heroku/brew, homebrew/core, homebrew/cask and homebrew/services).

==> New Formulae

atuin               gitbackup           mathlibtools        rmw

autoconf@2.69       gitwatch            neovim-remote       search-that-hash

cadical             gradle@6            nomino              tbb@2020

clazy               grepip              opensearch          trojan-go

ehco                ipinfo-cli          parquet-cli         zellij

elan-init           julia               php-cs-fixer@2

erlang@23           marp-cli            proj@7

==> Updated Formulae

heroku/brew/heroku                     lighttpd

libidn2                                 linkerd

mysql                                   llvm

postgresql                             lmod

protobuf                               log4cxx

abcmidi                                  logrotate

ace                                      lsix

allure                                   lttng-ust

amqp-cpp                                 luajit-openresty

angular-cli                              lynis

ansible                                  macchina

ansible-lint                             mapcidr

apache-arrow                             mapnik

apidoc                                   mapserver

apollo-cli                               mariadb-connector-c

aravis                                   marked

arduino-cli                              matplotplusplus

argo                                     mavsdk

argocd                                   md4c

armadillo                                mdbook

artifactory                              mermaid-cli

arturo                                   mesa

asciiquarium                             metabase

asdf                                     mhonarc

asio                                     micro

atkmm                                    microplane

atkmm@2.28                               mingw-w64

audacious                                minio

autorest                                 minio-mc

autorestic                               mitmproxy

aws-cdk                                  mjpegtools

aws-sdk-cpp                              mkvalidator

awscli                                   mkvtoolnix

awscli@1                                 mlt

awsume                                   mm-common

b2-tools                                 moarvm

babel                                    mockolo

bat                                      molecule

bazel                                    molten-vk

bazelisk                                 monero

bear                                     monetdb

benthos                                  mosh

bettercap                                moto

bind                                     mpd

bitcoin                                  mpg123

bitrise                                  mvnvm

bitwarden-cli                            mysql++

black                                    mysql-client

bloaty                                   mysql-connector-c++

bluepill                                 name-that-hash

blueutil                                 nativefier

bowtie2                                  nats-server

broot                                    nco

bullet                                   ncspot

bundletool                               ne

byacc                                    nebula

byteman                                  netlify-cli

caddy                                    netpbm

cadence                                  newrelic-cli

cadence-workflow                         nfdump

caf                                      ngt

caffe                                    nift

cairomm                                  node

cairomm@1.14                             node-build

cargo-c                                  node-sass

cargo-instruments                        node@14

cartridge-cli                            nodeenv

cbmc                                     nomad

cdogs-sdl                                notmuch

ceres-solver                             notmuch-mutt

cfn-lint                                 nqp

chart-testing                            nss

checkov                                  nuclei

cherrytree                               nuget

chezmoi                                  numcpp

chibi-scheme                             numpy

chrony                                   nushell

ckan                                     nvc

cloc                                     oauth2l

clojure                                  oci-cli

clojure-lsp                              ocp

clojurescript                            ocrmypdf

cloudformation-cli                       octant

cloudformation-guard                     odpi

cmusfm                                   oil

code-server                              okteto

comby                                    ola

commandbox                               open-image-denoise

composer                                 open-zwave

contentful-cli                           opencascade

cookiecutter                             opencv

copilot                                  opencv@3

cortex                                   openexr

cpplint                                  openfast

crane                                    openimageio

croc                                     openldap

cromwell                                 openvdb

crowdin                                  operator-sdk

crystal                                  or-tools

cubejs-cli                               osc

cubelib                                  osm

curaengine                               osm-pbf

curl                                     osm2pgsql

daemon                                   osmcoastline

darcs                                    ospray

dartsim                                  osrm-backend

datalad                                  pagmo

dav1d                                    pam_yubico

dbdeployer                               pandoc-plot

delve                                    pango

deno                                     pangomm

detekt                                   pangomm@2.46

devspace                                 parallelstl

dialog                                   pcapplusplus

diffoscope                               pdal

distcc                                   pdm

django-completion                        pdnsrec

djl-serving                              percona-server

dnscontrol                               percona-toolkit

dnsdist                                  percona-xtrabackup

docker-compose                           perl

docker-compose-completion                pgpool-ii

docker-machine-driver-vmware             pgroonga

doctl                                    php

dolt                                     php-code-sniffer

dprint                                   php@7.2

driftctl                                 php@7.3

dscanner                                 php@7.4

dssim                                    phpmd

duck                                     phpstan

duplicity                                phpunit

dvc                                      picard-tools

dxpy                                     pidgin

dyld-headers                             pinentry-mac

earthly                                  pipgrip

eccodes                                  plantuml

efl                                      pngquant

efm-langserver                           pnpm

ejdb                                     po4a

eksctl                                   points2grid

eless                                    postgis

elixir                                   postgresql@10

embree                                   postgresql@11

embulk                                   postgresql@12

emscripten                               postgresql@9.6

envoy                                    pre-commit

enzyme                                   prestodb

erlang                                   procs

erlang@21                                proj

erlang@22                                prometheus

eslint                                   prometheus-cpp

etcd                                     proper

etl                                      protobuf-c

exiftool                                 protoc-gen-go

exim                                     protoc-gen-go-grpc

expat                                    protoc-gen-gogo

exploitdb                                protoc-gen-gogofaster

extra-cmake-modules                      protoc-gen-grpc-web

fantom                                   psqlodbc

fastlane                                 pssh

fauna-shell                              ptex

fava                                     publish

feh                                      pulumi

findomain                                pushpin

firebase-cli                             putty

fish                                     pyenv

fizz                                     pympress

flarectl                                 pyqt

flatbuffers                              pyqt-3d

flow                                     pyqt-builder

flow-cli                                 pyqt-networkauth

fltk                                     pyqt@5

fluent-bit                               python-tk@3.9

flux                                     qbs

flyway                                   qcachegrind

fnm                                      qjackctl

folly                                    qmmp

fonttools                                qpdf

fplll                                    qt

freeciv                                  questdb

freeipmi                                 r

freeradius-server                        radare2

functionalplus                           rakudo

futhark                                  rbspy

fzf                                      rebar3

gatsby-cli                               remind

gcc@8                                    reminiscence

gdal                                     repo

gdu                                      richmd

geoserver                                rlwrap

gh                                       robot-framework

ghostscript                              root

ghq                                      rosa-cli

git-quick-stats                          roswell

gitlab-runner                            ruby-build

gitmoji                                  rustup-init

glab                                     rxvt-unicode

glib                                     s2n

glibmm                                   s3cmd

glibmm@2.66                              sassc

glog                                     sbtenv

glooctl                                  sbuild

gmt                                      scala

gmt@5                                    scalaenv

gnu-chess                                seal

gnuradio                                 sec

gnustep-make                             semgrep

go-boring                                seqkit

gofish                                   serverless

golangci-lint                            shfmt

goreleaser                               shibboleth-sp

gradle                                   shogun

gradle-profiler                          signal-cli

grafana                                  simdjson

grokj2k                                  simple-tiles

gromacs                                  sip

groonga                                  six

grpc                                     skaffold

grpc-swift                               skopeo

gtkmm3                                   sn0int

gtkmm4                                   snakemake

guile                                    sngrep

hadolint                                 snort

halide                                   snowpack

hamlib                                   sonarqube

haproxy                                  sourcery

haskell-stack                            spack

haxe                                     spatialite-gui

hblock                                   spatialite-tools

hcxtools                                 sphinx-doc

heimdal                                  squid

heksa                                    ssh-vault

helmfile                                 sslyze

helmsman                                 sstp-client

help2man                                 starship

highlight                                stellar-core

howard-hinnant-date                      stern

html-xml-utils                           streamlink

htmldoc                                  subversion

httpd                                    suite-sparse

i2p                                      svtplay-dl

i2pd                                     swift-format

imagemagick                              swift-protobuf

imagemagick@6                            swiftformat

imath                                    synfig

inetutils                                sysdig

influxdb                                 sysstat

inspircd                                 tanka

ioctl                                    taskwarrior-tui

iozone                                   tass64

ipv6calc                                 tbb

isl                                      tcsh

istioctl                                 tctl

jbake                                    telegraf

jc                                       terraform

jdupes                                   terraform-ls

jenkins                                  terragrunt

jetty                                    terrascan

jetty-runner                             testssl

jfrog-cli                                texlab

jose                                     texmath

jsdoc3                                   tfsec

jupyterlab                               thanos

just                                     threadweaver

k3d                                      tile38

k3sup                                    timelimit

k6                                       tintin

k9s                                      tinyproxy

karchive                                 tinyxml2

kcgi                                     todoman

kdoctools                                tomcat

keptn                                    tomcat@8

ki18n                                    tomcat@9

kind                                     topgrade

knot                                     tor

ko                                       torchvision

kops                                     trafficserver

kube-linter                              trash-cli

kubeaudit                                tree-sitter

kubecfg                                  triangle

kubergrunt                               truffle

kubernetes-cli                           tvnamer

kubeseal                                 twarc

kubevela                                 txr

kumactl                                  ugrep

kustomize                                ungit

kyma-cli                                 unum

lab                                      urh

latexindent                              usbredir

latino                                   v8

lean                                     vapoursynth-imwri

lean-cli                                 vapoursynth-ocr

lefthook                                 vapoursynth-sub

libbi                                    vim

libcouchbase                             vips

libdrm                                   vnstat

libepoxy                                 vroom

libetonyek                               vulkan-headers

libgaiagraphics                          wangle

libgeotiff                               wartremover

libgxps                                  watchexec

libidn                                   watson

libimagequant                            weechat

libmwaw                                  whistle

libopenmpt                               wildfly-as

libpano                                  wp-cli

libphonenumber                           wren

libpq                                    wtfutil

libpqxx                                  wxmaxima

libpulsar                                xcodegen

librasterlite                            xfig

librdkafka                               xh

libsass                                  xmake

libsigc++                                xplr

libsigc++@2                              xray

libslirp                                 xrootd

libspatialite                            yaz

libspectre                               ykdl

libtasn1                                 ykman

libtcod                                  yle-dl

libtensorflow                            youtube-dl

libtirpc                                 youtubedr

libtorch                                 yq

libunwind-headers                        zabbix

libupnp                                  zbackup

libvirt                                  zeek

libwebm                                  zile

libx11                                   zlib-ng

libxlsxwriter                            zstd

==> Deleted Formulae

erlang@20                                osquery

==> New Casks

android-commandlinetools   jidusm                     shortcutor

beeper                     mambaforge                 tint

enclave                    mem                        vamiga

hightop                    menu-bar-splitter          vitalsigns

instatus-out               privileges                 waltr-pro

jamkazam                   qudedup-extract-tool

jgrennison-openttd         safe-multisig

==> Updated Casks

1password

4k-stogram

4k-video-downloader

4k-youtube-to-mp3

a-better-finder-rename

activedock

adobe-acrobat-reader

adobe-connect

aerial

ajour

alacritty

alfaview

alt-tab

altair-graphql-client

amadine

amazon-chime

amazon-music

anaconda

android-studio

anka-build-cloud-controller-and-registry

anka-build-cloud-registry

anka-virtualization

anki

another-redis-desktop-manager

anydo

appcode

archipelago

arduino

aria-maestosa

arq

arrsync

atom

atomic-wallet

audioslicer

avidemux

avogadro

axe-edit-iii

azure-data-studio

backblaze

badlion-client

baidunetdisk

balance-lock

balenaetcher

banksiagui

bbc-iplayer-downloads

beatunes

beekeeper-studio

berrycast

binance

bit-slicer

bitwarden

blisk

blitz

blobby-volley2

blocs

blueharvest

bluewallet

bootstrap-studio

brave-browser

breakaway

browserosaurus

burp-suite

butt

buttercup

cacher

calibre

calmly-writer

camed

camo-studio

camtasia

camunda-modeler

canva

caramba-switcher

carbon-copy-cloner

catch

cctalk

chatterino

checkra1n

chia

chirp

chromedriver

chromium

chronycontrol

citra

clash-for-windows

cleanshot

clicker-for-youtube

clover-configurator

cocoapods

cog

commander-one

connectiq

cookie

coscreen

cozy-drive

cuda-z

curiosity

cyberduck

daedalus-mainnet

db-browser-for-sqlite

dbeaver-community

dbvisualizer

dcp-o-matic-player

dd-utility

decrediton

default-folder-x

devonthink

dhs

dingtalk

do-not-disturb

dotnet

dotnet-sdk

double-commander

downie

drawio

dropbox

drovio

edfbrowser

electerm

electron

element

eloston-chromium

emclient

epichrome

eul

exodus

fabfilter-timeless

fawkes

fedora-media-writer

feishu

fellow

ff-works

figma

fireworks

fl-studio

flipper

flock

flutter

folx

fontgoggles

foobar2000

forecast

foxmail

fredm-fuse

freecol

freeplane

freesmug-chromium

freetube

fsnotes

futubull

gather

gdat

gemini

gitkraken

glyphs

gns3

godot

godot-mono

goodsync

google-chrome

google-drive

gplates

grandperspective

grandtotal

gretl

grids

ha-menu

hackintool

hazel

helo

home-assistant

hook

hookshot

hstracker

hugin

ibackup-viewer

iconjar

iina-plus

imdone

imgotv

impactor

insync

iris

irpf2021

isimulator

itch

iterm2

ivideonclient

j

jami

jamovi

jamulus

jasper

jedit

jedit-omega

joplin

katalon-studio

kdiff3

keep-it

keeweb

kextviewr

keypad-layout

kicad

kid3

kinza

klatexformula

knime

knockknock

kodi

koodo-reader

krisp

laravel-kit

lark

lastpass

league-of-legends

lightkey

loaf

lockdown

loginputmac

loom

lrtimelapse

lunar-client

macfuse

macmediakeyforwarder

macupdater

magicavoxel

malwarebytes

mame

mathinspector

mcedit

media-converter

mediahuman-youtube-downloader

meetingbar

melodics

mendeley-reference-manager

meshlab

meta

metabase

metashape

metashapepro

metasploit

meteorologist

microsoft-auto-update

microsoft-edge

microsoft-excel

microsoft-office

microsoft-outlook

microsoft-powerpoint

microsoft-teams

microsoft-word

middle

milanote

minecraft

minecraft-server

miniforge

mirrorop

missive

mkvtoolnix

mmhmm

mnemosyne

mobirise

mochi

mockoon

mockuuups-studio

modelio

modern-csv

monero-wallet

moneydance

motrix

mountain-duck

mplab-xc32

mplabx-ide

mps

mqttx

mtgaprotracker

mubu

multipatch

multitouch

mumble

mycrypto

mysqlworkbench

nano

navicat-premium

netdownloadhelpercoapp

netiquette

netron

netxms-console

nomachine

nomachine-enterprise-client

nordpass

noxappplayer

nwjs

obsidian

ocenaudio

odrive

opencore-configurator

openwebstart

openzfs

opera

optimage

origami-studio

osxfuse

oversight

p4v

packet-peeper

pagico

papers

pdfsam-basic

peakhour

pgadmin4

pitch

plasticscm-cloud-edition

plex-media-server

plotdigitizer

podolski

pokerth

pop

porting-kit

postman

praat

pragli

preform

prepros

prey

principle

pritunl

projectlibre

propresenter

protonvpn

proxyman

prudent

puppetry

pushplaylabs-sidekick

qfinder-pro

qownnotes

qqmusic

qsync-client

quakespasm

quicken

qxmledit

r

radarr

ransomwhere

raven-reader

raycast

rcse

react-native-debugger

reaper

recaf

rectangle

recut

reikey

remnote

remote-desktop-manager

remote-desktop-manager-free

retroarch

retroarch-metal

rhino

ridibooks

rocket-chat

rolisteam

royal-tsx

scidvsmac

scratch

screaming-frog-seo-spider

screenflick

screens

seafile-client

seaglass

sensei

sentinel

sequel-ace

session

shift

sidequest

signal

silo

simplenote

simtoolkitpro

sipgate-softphone

sizzy

sketch

skype

slack

slippi-dolphin

softorino-youtube-converter

solar2d

spark-ar-studio

spectx

spotify

spyder

sqlpro-for-mssql

sqlpro-for-mysql

sqlpro-for-postgres

sqlpro-studio

standard-notes

stats

steam

stoplight-studio

streamlabs-obs

studio-3t

subgit

subler

sublime-merge

sublime-text

swiftformat-for-xcode

swinsian

switchhosts

syncterm

syncthing

syntax-highlight

tableau

tableau-prep

tales-of-majeyal

taskexplorer

telavox-flow

tempo

terminus

termius

texstudio

thorium

thunder

thunderbird

tidepool-uploader

time-to-leave

timeular

tinkerwell

torguard

tortoisehg

touch-bar-simulator

touchdesigner

tradingview

trailer

trainerroad

trilium-notes

tuple

turbovnc-viewer

tuxguitar

twine

twitterrific

tyme

typora

ultimaker-cura

ultimate

unity

unity-appletv-support-for-editor

unity-ios-support-for-editor

upm

upwork

usenapp

utm

valentina-studio

versions

vidcutter

virtualc64

virtualgl

visual

visual-paradigm

visual-paradigm-ce

visual-studio

visual-studio-code

vivaldi

vlc

vmpk

vmware-fusion

volanta

vrew

vscodium

vuescan

wavebox

webarchiveextractor

webcatalog

webex

webull

wechat

wechatwebdevtools

whatsapp

whatsyoursign

wire

workflowy

wowup

xamarin-workbooks

xampp

xca

yacreader

yate

yesplaymusic

yinxiangbiji

yuque

zalo

zecwallet-lite

zeplin

zerotier-one

zettlr

zoc

==> Deleted Casks

audiobookbinder            cellery                    opennx

 

You have 12 outdated formulae installed.

You can upgrade them with brew upgrade

or list them with brew outdated.

Error: homebrew/versions was deprecated. This tap is now empty and all its contents were either deleted or migrated.

mysql: stable 8.0.25 (bottled)

Open source relational database management system

https://dev.mysql.com/doc/refman/8.0/en/

Conflicts with:

  mariadb (because mysql, mariadb, and percona install the same binaries)

  percona-server (because mysql, mariadb, and percona install the same binaries)

/usr/local/Cellar/mysql/8.0.23_1 (298 files, 297.7MB) *

  Poured from bottle on 2021-03-21 at 15:05:59

From: https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/mysql.rb

License: GPL-2.0-only with Universal-FOSS-exception-1.0

==> Dependencies

Build: cmake , pkg-config

Required: icu4c , libevent , lz4 , openssl@1.1 , protobuf , zstd

==> Caveats

We've installed your MySQL database without a root password. To secure it run:

    mysql_secure_installation

 

MySQL is configured to only allow connections from localhost by default

 

To connect run:

    mysql -uroot

 

To have launchd start mysql now and restart at login:

  brew services start mysql

Or, if you don't want/need a background service you can just run:

  mysql.server start

==> Analytics

install: 75,051 (30 days), 242,047 (90 days), 901,197 (365 days)

install-on-request: 74,383 (30 days), 239,825 (90 days), 884,008 (365 days)

build-error: 0 (30 days)

==> Downloading https://ghcr.io/v2/homebrew/core/icu4c/manifests/69.1

######################################################################## 100.0%

==> Downloading https://ghcr.io/v2/homebrew/core/icu4c/blobs/sha256:d46b8ec5c3db

==> Downloading from https://pkg-containers.githubusercontent.com/ghcr1/blobs/sh

######################################################################## 100.0%

==> Downloading https://ghcr.io/v2/homebrew/core/libevent/manifests/2.1.12

######################################################################## 100.0%

==> Downloading https://ghcr.io/v2/homebrew/core/libevent/blobs/sha256:45758b448

==> Downloading from https://pkg-containers.githubusercontent.com/ghcr1/blobs/sh

######################################################################## 100.0%

==> Downloading https://ghcr.io/v2/homebrew/core/lz4/manifests/1.9.3

######################################################################## 100.0%

==> Downloading https://ghcr.io/v2/homebrew/core/lz4/blobs/sha256:7024d0b6ee8573

==> Downloading from https://pkg-containers.githubusercontent.com/ghcr1/blobs/sh

######################################################################## 100.0%

==> Downloading https://ghcr.io/v2/homebrew/core/six/manifests/1.16.0_1

######################################################################## 100.0%

==> Downloading https://ghcr.io/v2/homebrew/core/six/blobs/sha256:6068e58ff59ea7

==> Downloading from https://pkg-containers.githubusercontent.com/ghcr1/blobs/sh

######################################################################## 100.0%

==> Downloading https://ghcr.io/v2/homebrew/core/protobuf/manifests/3.17.0_1

######################################################################## 100.0%

==> Downloading https://ghcr.io/v2/homebrew/core/protobuf/blobs/sha256:854c7a9b9

==> Downloading from https://pkg-containers.githubusercontent.com/ghcr1/blobs/sh

######################################################################## 100.0%

==> Downloading https://ghcr.io/v2/homebrew/core/zstd/manifests/1.5.0

######################################################################## 100.0%

==> Downloading https://ghcr.io/v2/homebrew/core/zstd/blobs/sha256:eae17621cfc66

==> Downloading from https://pkg-containers.githubusercontent.com/ghcr1/blobs/sh

######################################################################## 100.0%

==> Downloading https://ghcr.io/v2/homebrew/core/mysql/manifests/8.0.25_1

######################################################################## 100.0%

==> Downloading https://ghcr.io/v2/homebrew/core/mysql/blobs/sha256:db388d333de4

==> Downloading from https://pkg-containers.githubusercontent.com/ghcr1/blobs/sh

######################################################################## 100.0%

Error: mysql 8.0.23_1 is already installed

To upgrade to 8.0.25_1, run:

  brew upgrade mysql

 

その後、mysql 起動

mysql.server start

Starting MySQL

 SUCCESS! 

 

セキュリティ周りの初期設定

mysql_secure_installation

Securing the MySQL server deployment.

===============================================

 

Enter password for user root: 

設定していたパスワード入力

VALIDATE PASSWORD COMPONENT can be used to test passwords

and improve security. It checks the strength of password

and allows the users to set only those passwords which are

secure enough. Would you like to setup VALIDATE PASSWORD component?

 

Press y|Y for Yes, any other key for No: 

yと入力

 y

 

There are three levels of password validation policy:

 

LOW    Length >= 8

MEDIUM Length >= 8, numeric, mixed case, and special characters

STRONG Length >= 8, numeric, mixed case, special characters and dictionary                  file

 

Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 

2を入力+エンター

Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 2   

 

Using existing password for root.

 

Estimated strength of the password: 25 

yを入力

Change the password for root ? *1/opt/anaconda3/lib/python3.8/site-packages/MySQLdb/__init__.py", line 130, in Connect

    return Connection(*args, **kwargs)

  File "/Users/*2/opt/anaconda3/lib/python3.8/site-packages/MySQLdb/connections.py", line 185, in __init__

    super().__init__(*args, **kwargs2)

MySQLdb._exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)")

(base) *3@MacBook-Air2020-2 Todoアプリ %

 

 

おそらくこのエラー

解決策は書いていなかった

dev.mysql.com

==================================

↓面白そうなサイト

docs.oracle.com

==================================

下記URLで色々試す

stackoverflow.com

 

vi netstat -nlp

f:id:chocolate22554:20210324211125p:plain

 

mysql_config --socket

 ↓

/tmp/mysql.sock

 

python db.py

Traceback (most recent call last):

  File "db.py", line 16, in <module>

    if conn_f():

  File "db.py", line 4, in conn_f

    con = MySQLdb.connect(

  File "/Users/*4/opt/anaconda3/lib/python3.8/site-packages/MySQLdb/__init__.py", line 130, in Connect

    return Connection(*args, **kwargs)

  File "/Users/*5/opt/anaconda3/lib/python3.8/site-packages/MySQLdb/connections.py", line 185, in __init__

    super().__init__(*args, **kwargs2)

MySQLdb._exceptions.OperationalError: (1045, "Access denied for user 'root@localhost'@'localhost' (using password: YES)")

(base) *6@MacBook-Air2020-2 Todoアプリ %

 

これは駄目だった

f:id:chocolate22554:20210324214137p:plain

 

おそらく  user とhostの部分が間違っている_

 

 

pip config

ERROR: Need an action (debug, edit, get, list, set, unset) to perform

 

 

 

$ mysql.server restart
の後に
$ mysql -u root -p

mysqlが起動できない - Qiita

 

 

use todo_app;

f:id:chocolate22554:20210412172721p:plain

MySQLで新しいユーザーを作成して権限を付与する方法 | DigitalOcean

 

(base) <<user name>>@MacBook-Air2020-2 Todoアプリ % python db.py

f:id:chocolate22554:20210412174629p:plain

そして成功した!

userのとこを"localhost"にしていたので普通にroot で良かったらしい

SQLのuser一覧表示してひたすら一覧のを当てはめていた^^;

f:id:chocolate22554:20210412174914p:plain

 

 ===================================

 

htmlファイルの作成

 

db.pyと同じフォルダに、templatesフォルダを作成

index.htmlを作成

f:id:chocolate22554:20210524180919p:plain

下記コード↓

<head>
<meta charset="UTF-8">
</head>

<!DOCTYPE html>
<html lang="ja">
<head>
<title>ToDoアプリケーション</title>
<style>
#main {
width: 60%;
border: solid 1px #ccc;
margin: 0 auto;
text-align: center;
}
form , h1, p{
margin: 0 auto;
text-align: center;
}
hr {
width: 50%;
}
</style>
</head>
<body>

<div id="main">
<form method="POST">
<input type="text" name="content" size="35" placeholder="17:00までに牛乳を1本買う"><br>
<input type="submit" value="追加">
</form>

<h1>TODO</h1>
<hr>
<h1>完了したTODO</h1>
</div>
</body>
</html>

 

f:id:chocolate22554:20210419162728p:plain

  • <head>
  •   <meta charset="UTF-8">
  • </head>

入れないと文字化けする

 

 

ブラウザで表示

f:id:chocolate22554:20210524181510p:plain

 

タスクの追加

main.pyを作成

f:id:chocolate22554:20210524181651p:plain

コード↓

# 1.必要なモジュールの読み込み
from flask import Flask, request,redirect, url_for, Response,render_template
from db import conn_f
from datetime import datetime as dt

date = dt.now().strftime('%Y:%m:%d %H:%I:%S')

# 2. Flaskを使うためのおまじない
app = Flask(__name__)

# 3.taskテーブルから完了していないtaskを取得する関数
def get_all_tasks():
conn = conn_f()
cursor = conn.cursor()
# user_idを使う場合(今回はこのsqlは実行しません)
# sql = 'select task_id,task_content,done_flag,created_at from todo where user_id= {0};'.format(user_id)
sql = 'select task_id,task_content,done_flag,created_at from todo where done_flag = 0;'
cursor.execute(sql)
tasks = cursor.fetchall()

cursor.close()
conn.close()
return tasks

# 4.taskテーブルから完了しているtaskを取得する関数
def get_all_done_tasks():
conn = conn_f()
cursor = conn.cursor()
# user_idを使う場合(今回はこのsqlは実行しません)
# sql = 'select task_id,task_content,done_flag,created_at from todo where user_id= {0};'.format(user_id)
sql = 'select task_id,task_content,done_flag,created_at from todo where done_flag = 1;'
cursor.execute(sql)
tasks = cursor.fetchall()

cursor.close()
conn.close()
return tasks

# 5. /にアクセスした時に実行されるindex関数
@app.route('/', methods=['GET'])
def index():
tasks = get_all_tasks()
done_tasks = get_all_done_tasks()
# index.htmlにはリストを渡す
return render_template('index.html', tasks=list(tasks), done_tasks=list(done_tasks))

# 6. TODO(タスク)の追加処理
@app.route('/', methods=['GET','POST'])
def add():
conn = conn_f()
cursor = conn.cursor()
sql = 'insert into todo(task_content,done_flag,created_at) values("{0}", {1}, "{2}");'.format(
request.form['content'],
0,
date)
cursor.execute(sql)
conn.commit()

# 接続を閉じる
cursor.close()
conn.close()

# index.htmlにはリストを渡す
tasks = get_all_tasks()
done_tasks = get_all_done_tasks()
# index.htmlにはリストを渡す
return render_template('index.html', tasks=list(tasks), done_tasks=list(done_tasks))

if __name__ == '__main__':
app.run( port=8000)

 

 

index.htmlを修正

赤枠部分を削除

f:id:chocolate22554:20210524182614p:plain

下記コードを追加

 

<div id="main">
<form method="POST">
<input type="text" name="content" size="35" placeholder="17:00までに牛乳を1本買う"><br>
<input type="submit" value="追加">
</form>

<h1>TODO</h1>

{% for task in tasks %}
<form method="post" action="/update">
<input type="text" name="content" value="{{ task[1] }}">
<input type="hidden" name="task_id" value="{{ task[0] }}">
<input type="submit" value="更新" class="btn">
</form>

<form method="post" action="done">
<input type="hidden" name="task_id" value="{{ task[0] }}">
<input type="submit" value="完了" class="btn">
</form>
<hr>

{% endfor %}
</div>

 

 

python main.py       を実行

 * Serving Flask app "main" (lazy loading)

 * Environment: production

   WARNING: This is a development server. Do not use it in a production deployment.

   Use a production WSGI server instead.

 * Debug mode: off

 * Running on http://127.0.0.1:8000/ (Press CTRL+C to quit)

127.0.0.1 - - [24/May/2021 19:02:24] "GET / HTTP/1.1" 200 -

 

ブラウザでhttp://127.0.0.1:8000/にアクセス

 

f:id:chocolate22554:20210524190613p:plain

===================================

* Serving Flask app "main" (lazy loading)

 * Environment: production

   WARNING: This is a development server. Do not use it in a production deployment.

   Use a production WSGI server instead.

 * Debug mode: off

 * Running on http://127.0.0.1:8000/ (Press CTRL+C to quit)

[2021-05-24 18:31:15,981] ERROR in app: Exception on / [GET]

Traceback (most recent call last):

  File "/Users/●●/opt/anaconda3/lib/python3.8/site-packages/flask/app.py", line 2447, in wsgi_app

    response = self.full_dispatch_request()

  File "/Users/●●/opt/anaconda3/lib/python3.8/site-packages/flask/app.py", line 1952, in full_dispatch_request

    rv = self.handle_user_exception(e)

  File "/Users/●●/opt/anaconda3/lib/python3.8/site-packages/flask/app.py", line 1821, in handle_user_exception

    reraise(exc_type, exc_value, tb)

  File "/Users/●●/opt/anaconda3/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise

    raise value

  File "/Users/●●/opt/anaconda3/lib/python3.8/site-packages/flask/app.py", line 1950, in full_dispatch_request

    rv = self.dispatch_request()

  File "/Users/●●/opt/anaconda3/lib/python3.8/site-packages/flask/app.py", line 1936, in dispatch_request

    return self.view_functions[rule.endpoint](**req.view_args)

  File "main.py", line 45, in index

    return render_template('index.html', tasks=list(tasks), done_tasks=list(done_tasks))

  File "/Users/●●/opt/anaconda3/lib/python3.8/site-packages/flask/templating.py", line 138, in render_template

    ctx.app.jinja_env.get_or_select_template(template_name_or_list),

  File "/Users/●●/opt/anaconda3/lib/python3.8/site-packages/jinja2/environment.py", line 930, in get_or_select_template

    return self.get_template(template_name_or_list, parent, globals)

  File "/Users/●●/opt/anaconda3/lib/python3.8/site-packages/jinja2/environment.py", line 883, in get_template

    return self._load_template(name, self.make_globals(globals))

  File "/Users/●●/opt/anaconda3/lib/python3.8/site-packages/jinja2/environment.py", line 857, in _load_template

    template = self.loader.load(self, name, globals)

  File "/Users/●●/opt/anaconda3/lib/python3.8/site-packages/jinja2/loaders.py", line 127, in load

    code = environment.compile(source, name, filename)

  File "/Users/●●/opt/anaconda3/lib/python3.8/site-packages/jinja2/environment.py", line 638, in compile

    self.handle_exception(source=source_hint)

  File "/Users/●●/opt/anaconda3/lib/python3.8/site-packages/jinja2/environment.py", line 832, in handle_exception

    reraise(*rewrite_traceback_stack(source=source))

  File "/Users/●●/opt/anaconda3/lib/python3.8/site-packages/jinja2/_compat.py", line 28, in reraise

    raise value.with_traceback(tb)

  File "/Users/●●/△△/Todoアプリ AIacademy/templates/index.html", line 39, in template

    <input type="hidden" name="task_id" value="{{ task[0] }}">

jinja2.exceptions.TemplateSyntaxError: Unexpected end of template. Jinja was looking for the following tags: 'endfor' or 'else'. The innermost block that needs to be closed is 'for'.

127.0.0.1 - - [24/May/2021 18:31:16] "GET / HTTP/1.1" 500 -

127.0.0.1 - - [24/May/2021 18:31:16] "GET /apple-touch-icon-precomposed.png HTTP/1.1" 404 -

127.0.0.1 - - [24/May/2021 18:31:16] "GET /apple-touch-icon.png HTTP/1.1" 404 -

127.0.0.1 - - [24/May/2021 18:31:16] "GET /favicon.ico HTTP/1.1" 404 -

 

 

 

アプリケーションのエラー — Flask Documentation (1.1.x)

f:id:chocolate22554:20210524185553p:plain

 


f:id:chocolate22554:20210524184904p:plain

HTML - HTMLのIf文エラーへの対処|teratail

Pythonの文法とは異なりjinja2では{% elif ~ %}の後には{% endif %}行が必要です。

というコメントをヒントに

Jinja failing to parse conditions correctly. · Issue #29543 · saltstack/salt · GitHub

{% if grains['os'] == 'value1' %}  は {% endif %}  で終わらせる
    {% for instance in ['value2'] %}は
        Do stuff here<色々なコードを挟んで>
    {% endfor %}で終わらせる

 

===================================

Pythonをアップデートしよう ( 3.8.4 )-Lv.1からはじめるブログ

 pythonのアップデート

 

pipのインストール方法 - Qiita

  1. pip をインストールする
 
curl -kL https://bootstrap.pypa.io/get-pip.py | python

 

pipでアップデートするときのコマンド pip update - Qiita

 

パッケージのインストール

 
$ pip install <package-name>

pip自体のアップデート

$ pip install -U pip

アップデート必要なパッケージのリスト(これは便利)

 
$ pip list -o

 

jinjaがエラー出てたので

pip install jinja 実行

↓すさまじいエラーが出たので最後の2行だけ

ERROR: Could not find a version that satisfies the requirement jinja

ERROR: No matching distribution found for jinja

 

python -m pip install flask  だと動く

これをflaskをjinjaにするとやはり同じエラー

python - Could not find a version that satisfies the requirement <package> - Stack Overflow

===================================

 

TODO(タスク)の追加処理

 

main.py

return render_template('index.html', tasks=list(tasks), done_tasks=list(done_tasks))

 

の下に下記を追加

 

@app.route('/done', methods=['POST'])
def done():
conn = conn_f()
cursor = conn.cursor()
sql = 'UPDATE todo SET done_flag=1 where task_id={0};'.format(
request.form['task_id'])
cursor.execute(sql)
conn.commit()
cursor.close()
conn.close()

# indexにリダイレクト
return redirect(url_for('index'))

f:id:chocolate22554:20210524191210p:plain

 

 

index.html

{% endfor %}の下に下記コード追加

 

<h1>完了したTODO</h1>

{% for task in done_tasks %}
<p>{{ task[1] }}</p>
{% endfor %}

f:id:chocolate22554:20210524191629p:plain

 

タスクの更新

main.pyにupdateの部分を追加

 

  # indexにリダイレクト  return redirect(url_for('index'))の下に

f:id:chocolate22554:20210524192047p:plain

下記コードを追加

@app.route('/update', methods=['POST'])
def update():
conn = conn_f()
cursor = conn.cursor()
sql = 'UPDATE todo SET task_content="{0}" where task_id={1};'.format(
request.form['content'],
request.form['task_id'])
cursor.execute(sql)
conn.commit()
cursor.close()
conn.close()
tasks = get_all_tasks()
done_tasks = get_all_done_tasks()
# index.htmlにはリストを渡す
return render_template('index.html', tasks=list(tasks), done_tasks=list(done_tasks))

 

ブラウザには完了したTODOが付け加えられていた

f:id:chocolate22554:20210524192226p:plain

f:id:chocolate22554:20210524192300p:plain

==================================

ユーザー名とパスワードが必要なよう

MySQLでユーザー一覧を確認する「mysql.userテーブル」 | UX MILK

  ↓下記コマンド実行

mysql> SELECT Host, User FROM mysql.user;

 

+-----------+------------------+

 「::1」はIPv6におけるlocalhostで、「127.0.01」はIPv4におけるlocalhost

4 rows in set (0.00 sec)

 

暗号化済のパスワードを表示する

mysql> SELECT Host, User, Password FROM user WHERE User = "wordpress ";

ERROR 1146 (42S02): Table 'todo_app.user' doesn't exist

 自分ので何回か実行するがエラー 4つともすべて全滅

 

SHOW TABLES FROM も全滅

ERROR 1146 (42S02) : MySQL でいこう!

mysql> SHOW TABLES FROM database todo_app;

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'database todo_app' at line 1

 

とりあえず紛らわしいので遊びも兼ねてusername 変更

ユーザー名を変更する(RENAME USER文) | MySQLの使い方

rename user kitsune@localhost to ookami@localhost;

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.infoschema to first' at line 1

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds t

これもなんかエラー

 

コマンド実行

mysql -u root

↓パスワードさえ入れられない感じに

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

 

こちらで実行

mysql -u root -p

パスワード入力でmysqlにログインできる

 

忘れがちだがmysqlで実行するときは最後に; か\gをつける

Commands end with ; or \g.

 

 

ことごとくエラーが出る

MySQL :: MySQL 5.6 リファレンスマニュアル :: 6.2.7 アクセス拒否エラーの原因

mysql;

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'mysql' at line 1

 

 netstat -ln | grep mysql;

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MyS

  -> mysql -u root test;

 

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'mysql -u root test

mysql -u root test' at line 1

 

my sqlにはログインできている パスワードも正常

 

↓いつかまた見たいHP

https://style.potepan.com/articles/18389.html

 

mysql -u root - p

mysqlにログインできた

Enter password: 

Welcome to the MySQL monitor.  Commands end with ; or \g.

Your MySQL connection id is 11

Server version: 8.0.23 Homebrew

 

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

 

Oracle is a registered trademark of Oracle Corporation and/or its

affiliates. Other names may be trademarks of their respective

owners.

 

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

 

 

mysql> use todo_app;

Reading table information for completion of table and column names

You can turn off this feature to get a quicker startup with -A

 

Database changed

 

ユーザーの一覧や設定された権限などユーザーに関する情報を取得する | MySQLの使い方

                      現在接続しているユーザーを確認する

select user(), current_user();

+----------------+----------------+

| user()         | current_user() |

+----------------+----------------+

| root@jioja     | root@jioja     |

+----------------+----------------+

1 row in set (0.00 sec)

 

                      ユーザーに設定されている権限を確認する

SHOW GRANTS FOR root@jioja (user)

+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

| Grants for root@localhost                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |

+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

| GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, RELOAD, SHUTDOWN, PROCESS, FILE, REFERENCES, INDEX, ALTER, SHOW DATABASES, SUPER, CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE, REPLICATION SLAVE, REPLICATION CLIENT, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, CREATE USER, EVENT, TRIGGER, CREATE TABLESPACE, CREATE ROLE, DROP ROLE ON *.* TO `root`@`jioja ` WITH GRANT OPTION                                                                                                                                                                                                                    |

| GRANT APPLICATION_PASSWORD_ADMIN,AUDIT_ADMIN,BACKUP_ADMIN,BINLOG_ADMIN,BINLOG_ENCRYPTION_ADMIN,CLONE_ADMIN,CONNECTION_ADMIN,ENCRYPTION_KEY_ADMIN,FLUSH_OPTIMIZER_COSTS,FLUSH_STATUS,FLUSH_TABLES,FLUSH_USER_RESOURCES,GROUP_REPLICATION_ADMIN,INNODB_REDO_LOG_ARCHIVE,INNODB_REDO_LOG_ENABLE,PERSIST_RO_VARIABLES_ADMIN,REPLICATION_APPLIER,REPLICATION_SLAVE_ADMIN,RESOURCE_GROUP_ADMIN,RESOURCE_GROUP_USER,ROLE_ADMIN,SERVICE_CONNECTION_ADMIN,SESSION_VARIABLES_ADMIN,SET_USER_ID,SHOW_ROUTINE,SYSTEM_USER,SYSTEM_VARIABLES_ADMIN,TABLE_ENCRYPTION_ADMIN,XA_RECOVER_ADMIN ON *.* TO `root`@`jioja` WITH GRANT OPTION |

| GRANT PROXY ON ''@'' TO 'root'@'localhost' WITH GRANT OPTION                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |

+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

3 rows in set (0.00 sec)

 

==================================

python db.py

↓下記エラーが出たのでURL参考にする

Traceback (most recent call last):

  File "db.py", line 1, in <module>

    import MySQLdb

ModuleNotFoundError: No module named 'MySQLdb'

PythonでMySQLを操作する方法:MySQLdb | UX MILK

 

pip install MySQL-Python

Collecting MySQL-Python

  Downloading MySQL-python-1.2.5.zip (108 kB)

     |████████████████████████████████| 108 kB 186 kB/s 

    ERROR: Command errored out with exit status 1:

     command: /Users/(username)/opt/anaconda3/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-8sssiahf/mysql-python/setup.py'"'"'; __file__='"'"'/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-8sssiahf/mysql-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-pip-egg-info-2d5y1wqr

         cwd: /private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-8sssiahf/mysql-python/

    Complete output (7 lines):

    Traceback (most recent call last):

      File "<string>", line 1, in <module>

      File "/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-8sssiahf/mysql-python/setup.py", line 13, in <module>

        from setup_posix import get_config

      File "/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-8sssiahf/mysql-python/setup_posix.py", line 2, in <module>

        from ConfigParser import SafeConfigParser

    ModuleNotFoundError: No module named 'ConfigParser'

    ----------------------------------------

ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

 

============================================

pip - Pipインストールでエラー: “python setup.py egg_info” failed with error code 1 - スタック・オーバーフロー

pip install - -upgrade setuptools

 

Usage:   

  pip install [options] <requirement specifier> [package-index-options] ...

  pip install [options] -r <requirements file> [package-index-options] ...

  pip install [options] [-e] <vcs project url> ...

  pip install [options] [-e] <local project path> ...

  pip install [options] <archive url/path> ...

 

pip install - -upgrade pip

Usage:   

  pip install [options] <requirement specifier> [package-index-options] ...

  pip install [options] -r <requirements file> [package-index-options] ...

  pip install [options] [-e] <vcs project url> ...

  pip install [options] [-e] <local project path> ...

  pip install [options] <archive url/path> ...

 

no such option: -u

=====================================

こちらが良さげ

【Python】「Command "python setup.py egg_info" failed with error code 1 in ...」の対処法 - Knowhow,Nohow

pip、setuptoolsが最新ではない

pip install --upgrade pip setuptools 

Collecting pip

  Downloading pip-21.0.1-py3-none-any.whl (1.5 MB)

     |████████████████████████████████| 1.5 MB 498 kB/s 

Collecting setuptools

  Downloading setuptools-54.1.2-py3-none-any.whl (785 kB)

     |████████████████████████████████| 785 kB 73 kB/s 

Installing collected packages: pip, setuptools

  Attempting uninstall: pip

    Found existing installation: pip 20.2.4

    Uninstalling pip-20.2.4:

      Successfully uninstalled pip-20.2.4

  Attempting uninstall: setuptools

    Found existing installation: setuptools 50.3.1.post20201107

    Uninstalling setuptools-50.3.1.post20201107:

      Successfully uninstalled setuptools-50.3.1.post20201107

Successfully installed pip-21.0.1 setuptools-54.1.2

 

もう一度try 更にエラー文長くなった

pip install MySQL-Python

Collecting MySQL-Python

  Using cached MySQL-python-1.2.5.zip (108 kB)

    ERROR: Command errored out with exit status 1:

     command: /Users/(username)/opt/anaconda3/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_63981195ed56471eaf3a3e2b27d7b4bf/setup.py'"'"'; __file__='"'"'/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_63981195ed56471eaf3a3e2b27d7b4bf/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-pip-egg-info-m0zumxig

         cwd: /private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_63981195ed56471eaf3a3e2b27d7b4bf/

    Complete output (7 lines):

    Traceback (most recent call last):

      File "<string>", line 1, in <module>

      File "/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_63981195ed56471eaf3a3e2b27d7b4bf/setup.py", line 13, in <module>

        from setup_posix import get_config

      File "/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_63981195ed56471eaf3a3e2b27d7b4bf/setup_posix.py", line 2, in <module>

        from ConfigParser import SafeConfigParser

    ModuleNotFoundError: No module named 'ConfigParser'

    ----------------------------------------

WARNING: Discarding https://files.pythonhosted.org/packages/a5/e9/51b544da85a36a68debe7a7091f068d802fc515a3a202652828c73453cad/MySQL-python-1.2.5.zip#sha256=811040b647e5d5686f84db415efd697e6250008b112b6909ba77ac059e140c74 (from https://pypi.org/simple/mysql-python/). Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

  Downloading MySQL-python-1.2.4.zip (113 kB)

     |████████████████████████████████| 113 kB 751 kB/s 

    ERROR: Command errored out with exit status 1:

     command: /Users/(username)/opt/anaconda3/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_07757f14e04f4c24bcfef8dd525ff809/setup.py'"'"'; __file__='"'"'/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_07757f14e04f4c24bcfef8dd525ff809/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-pip-egg-info-hc626mr4

         cwd: /private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_07757f14e04f4c24bcfef8dd525ff809/

    Complete output (31 lines):

    Downloading http://pypi.python.org/packages/source/d/distribute/distribute-0.6.28.tar.gz

    Traceback (most recent call last):

      File "/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_07757f14e04f4c24bcfef8dd525ff809/distribute_setup.py", line 143, in use_setuptools

        raise ImportError

    ImportError

    

    During handling of the above exception, another exception occurred:

    

    Traceback (most recent call last):

      File "<string>", line 1, in <module>

      File "/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_07757f14e04f4c24bcfef8dd525ff809/setup.py", line 7, in <module>

        use_setuptools()

      File "/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_07757f14e04f4c24bcfef8dd525ff809/distribute_setup.py", line 145, in use_setuptools

        return _do_download(version, download_base, to_dir, download_delay)

      File "/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_07757f14e04f4c24bcfef8dd525ff809/distribute_setup.py", line 123, in _do_download

        tarball = download_setuptools(version, download_base,

      File "/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_07757f14e04f4c24bcfef8dd525ff809/distribute_setup.py", line 194, in download_setuptools

        src = urlopen(url)

      File "/Users/(username)/opt/anaconda3/lib/python3.8/urllib/request.py", line 222, in urlopen

        return opener.open(url, data, timeout)

      File "/Users/(username)/opt/anaconda3/lib/python3.8/urllib/request.py", line 531, in open

        response = meth(req, response)

      File "/Users/(username)/opt/anaconda3/lib/python3.8/urllib/request.py", line 640, in http_response

        response = self.parent.error(

      File "/Users/(username)/opt/anaconda3/lib/python3.8/urllib/request.py", line 569, in error

        return self._call_chain(*args)

      File "/Users/(username)/opt/anaconda3/lib/python3.8/urllib/request.py", line 502, in _call_chain

        result = func(*args)

      File "/Users/(username)/opt/anaconda3/lib/python3.8/urllib/request.py", line 649, in http_error_default

        raise HTTPError(req.full_url, code, msg, hdrs, fp)

    urllib.error.HTTPError: HTTP Error 403: SSL is required

    ----------------------------------------

WARNING: Discarding https://files.pythonhosted.org/packages/90/5a/ce7bef80825c2188cf507baf57b37516e18dffdb198a6766a597f703059a/MySQL-python-1.2.4.zip#sha256=e405f9d6be33923d428acaa4db4f4470427f1d15ea0d2d82a933449ace26bbd9 (from https://pypi.org/simple/mysql-python/). Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

  Downloading MySQL-python-1.2.3.tar.gz (70 kB)

     |████████████████████████████████| 70 kB 546 kB/s 

    ERROR: Command errored out with exit status 1:

     command: /Users/(username)/opt/anaconda3/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_209f4c0784f44e51abbf568ad50542d9/setup.py'"'"'; __file__='"'"'/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_209f4c0784f44e51abbf568ad50542d9/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-pip-egg-info-6s31mep7

         cwd: /private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_209f4c0784f44e51abbf568ad50542d9/

    Complete output (8 lines):

    Traceback (most recent call last):

      File "<string>", line 1, in <module>

      File "/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_209f4c0784f44e51abbf568ad50542d9/setup.py", line 11, in <module>

        from setup_posix import get_config

      File "/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_209f4c0784f44e51abbf568ad50542d9/setup_posix.py", line 101

        print """You shouldn't be running this directly; it is used by setup.py."""

              ^

    SyntaxError: Missing parentheses in call to 'print'. Did you mean print("""You shouldn't be running this directly)?

    ----------------------------------------

WARNING: Discarding https://files.pythonhosted.org/packages/9a/81/924d6799494cf7fb24370335c2f782088d6ac4f79e4137d4df94cea3582c/MySQL-python-1.2.3.tar.gz#sha256=7de66fbbf923634e7c965aeaefa74642ba75ae20ee1cefcefc3009595b7a7e6e (from https://pypi.org/simple/mysql-python/). Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

ERROR: Could not find a version that satisfies the requirement MySQL-Python

ERROR: No matching distribution found for MySQL-Python

 

 

 

pip3でmysql-connectorをインストールする方法 - Qiita

sudo pip3 install mysql-connector-python

↓パスワード入力を求められた

WARNING: The directory '/Users/(username)/Library/Caches/pip' or its parent directory is not owned or is not writable by the current user. The cache has been disabled. Check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

Collecting mysql-connector-python

  Downloading mysql_connector_python-8.0.23-cp38-cp38-macosx_10_14_x86_64.whl (4.9 MB)

     |████████████████████████████████| 4.9 MB 637 kB/s 

Requirement already satisfied: protobuf>=3.0.0 in /Users/(username)/opt/anaconda3/lib/python3.8/site-packages (from mysql-connector-python) (3.14.0)

Requirement already satisfied: six>=1.9 in /Users/(username)/opt/anaconda3/lib/python3.8/site-packages (from protobuf>=3.0.0->mysql-connector-python) (1.15.0)

Installing collected packages: mysql-connector-python

Successfully installed mysql-connector-python-8.0.23

 

sudo pip3 install mysql-connector-python-rf

 

WARNING: The directory '/Users/(username)/Library/Caches/pip' or its parent directory is not owned or is not writable by the current user. The cache has been disabled. Check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

Collecting mysql-connector-python-rf

  Downloading mysql-connector-python-rf-2.2.2.tar.gz (11.9 MB)

     |████████████████████████████████| 11.9 MB 644 kB/s 

Building wheels for collected packages: mysql-connector-python-rf

  Building wheel for mysql-connector-python-rf (setup.py) ... done

  Created wheel for mysql-connector-python-rf: filename=mysql_connector_python_rf-2.2.2-cp38-cp38-macosx_10_9_x86_64.whl size=249462 sha256=d8fc55ec78b1326372931f52376426059d84f2ac4938b7dabb01d7b2ad688073

  Stored in directory: /private/tmp/pip-ephem-wheel-cache-xq5gybwo/wheels/f5/66/87/6d9cef740fd440ef390930fdbe6c761dc1efef78ec94a288fd

Successfully built mysql-connector-python-rf

Installing collected packages: mysql-connector-python-rf

Successfully installed mysql-connector-python-rf-2.2.2

 

 

Python 3 ImportError: No module named 'ConfigParser' - Stack Overflow

    

 ModuleNotFoundError: No module named 'ConfigParser' ⇢mysqlclient 代わりに使わないといけない?

 

pip install mysqlclient

↓    

Collecting mysqlclient

  Downloading mysqlclient-2.0.3.tar.gz (88 kB)

     |████████████████████████████████| 88 kB 557 kB/s 

Building wheels for collected packages: mysqlclient

  Building wheel for mysqlclient (setup.py) ... done

  Created wheel for mysqlclient: filename=mysqlclient-2.0.3-cp38-cp38-macosx_10_9_x86_64.whl size=56300 sha256=24d4846b979e3cc86be56ebefe150d8a0b5aec74bce9d1fdc84bc2aa399cd1a7

  Stored in directory: /Users/●●/Library/Caches/pip/wheels/3a/c1/c3/5a19639a551c921c2c2b39468f4278ce5aa27b4e386a4158e4

Successfully built mysqlclient

Installing collected packages: mysqlclient

Successfully installed mysqlclient-2.0.3

 

 

 

 

 

 

 

 

 

 

AI Academy | テキスト

AI Academy | テキスト

*1:Press y|Y for Yes, any other key for No) : y

New password: 

===============================================

 

 mysql_secure_installation

 

Securing the MySQL server deployment.

 

Enter password for user root: 

The 'validate_password' component is installed on the server.

The subsequent steps will run with the existing configuration

of the component.

Using existing password for root.

 

Estimated strength of the password: 25 

Change the password for root ? ((Press y|Y for Yes, any other key for No) : s

 

 ... skipping.

By default, a MySQL installation has an anonymous user,

allowing anyone to log into MySQL without having to have

a user account created for them. This is intended only for

testing, and to make the installation go a bit smoother.

You should remove them before moving into a production

environment.

 

ここから先はずっと 「y」選択

 

Remove anonymous users? (Press y|Y for Yes, any other key for No) : y

Success.

 

 

Normally, root should only be allowed to connect from

'localhost'. This ensures that someone cannot guess at

the root password from the network.

 

Disallow root login remotely? (Press y|Y for Yes, any other key for No) : y

Success.

 

By default, MySQL comes with a database named 'test' that

anyone can access. This is also intended only for testing,

and should be removed before moving into a production

environment.

 

 

Remove test database and access to it? (Press y|Y for Yes, any other key for No) : y

 - Dropping test database...

Success.

 

 - Removing privileges on test database...

Success.

 

Reloading the privilege tables will ensure that all changes

made so far will take effect immediately.

 

Reload privilege tables now? (Press y|Y for Yes, any other key for No) : y

Success.

 

All done! 

Remove anonymous users? (Press y|Y for Yes, any other key for No) : y

Success.

 

 

Normally, root should only be allowed to connect from

'localhost'. This ensures that someone cannot guess at

the root password from the network.

 

Disallow root login remotely? (Press y|Y for Yes, any other key for No) : y

Success.

 

By default, MySQL comes with a database named 'test' that

anyone can access. This is also intended only for testing,

and should be removed before moving into a production

environment.

 

 

Remove test database and access to it? (Press y|Y for Yes, any other key for No) : y

 - Dropping test database...

Success.

 

 - Removing privileges on test database...

Success.

 

Reloading the privilege tables will ensure that all changes

made so far will take effect immediately.

 

Reload privilege tables now? (Press y|Y for Yes, any other key for No) : y

Success.

 

All done! 

 

 

mysql -u root -p

↓ パスワード入力しエンター

Enter password: 

Welcome to the MySQL monitor.  Commands end with ; or \g.

Your MySQL connection id is 21

Server version: 8.0.23 Homebrew

 

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

 

Oracle is a registered trademark of Oracle Corporation and/or its

affiliates. Other names may be trademarks of their respective

owners.

 

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

 

mysql> 

 

 

日本語化設定と暗号化プラグインの設定

my.cnfというファイル名で下記コードをテキストエディター作成。

# Default Homebrew MySQL server config
[mysqld]
# Only allow connections from localhost
bind-address = 127.0.0.1
character-set-server=utf8 # この行を追加
default_authentication_plugin=mysql_native_password # この行を追加

 

 下記 mysqlの状態から exitする

f:id:chocolate22554:20210524174232p:plain

mysql> Exit

Bye

 

サーバーを再起動

mysql.server restart

Shutting down MySQL

. SUCCESS! 

Starting MySQL

.. SUCCESS! 

 

サーバーの状態を確認

mysql.server status

 SUCCESS! MySQL running (31069)

 

サーバーをスタート

mysql.server start

Starting MySQL

 SUCCESS! 

2021-05-24T08:46:05.6NZ mysqld_safe A mysqld process already exists

 

(もしエラーがでた場合は、一度mysqlをstop

mysql.server stop

Shutting down MySQL

.. SUCCESS! 

 

mysql.server start

Starting MySQL

. SUCCESS!

 

mysql.server status

 SUCCESS! MySQL running (31315)   )

 

FlaskとMySQLでToDoアプリを実装しよう

   ↓下記コマンドMysqlコンソールを起動・実行

mysql -u root -p

↓パスワード入力

Enter password:

Welcome to the MySQL monitor.  Commands end with ; or \g.

Your MySQL connection id is 10

Server version: 8.0.23 Homebrew

 

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

 

Oracle is a registered trademark of Oracle Corporation and/or its

affiliates. Other names may be trademarks of their respective

owners.

 

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

 

mysql>

↓my sql シェルが開いた

 

 

todo_appというデータベースとtodoというテーブルを作成

todo_appデータベースを作成<mysql シェル?内>

mysql>  create database todo_app;

mysql> create database todo_app;

Query OK, 1 row affected (0.00 sec)

 

 

todo_appデータベースを使用するためにuseコマンド

use todo_app;

Database changed

 (Reading table information for completion of table and column names

You can turn off this feature to get a quicker startup with -A

 

Database changed)

 

todoテーブルを作成

mysql> create table todo(
task_id INT(10) primary key NOT NULL AUTO_INCREMENT,
task_content VARCHAR(200) NOT NULL,
done_flag INT(10) DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

Query OK, 0 rows affected, 2 warnings (0.03 sec)

 
 (すでにある場合:ERROR 1050 (42S01): Table 'todo' already exists
作成したカラムは、
task_id
task_content(todoの内容)
done_flag(完了したタスク⇢1 未完了⇢0が入る)
created_at(タスクを追加した時間)
の4つ
 

PythonMySQLでデータベースと接続

 

テキストエディタにて 「db.py」というタイトルをつけ該当ディレクトリに保存

↓中身

import MySQLdb

def conn_f():
con = MySQLdb.connect(
user="自分の username",
passwd="自分のpassword",
host="localhost",
db="todo_app",
charset="utf8"
)
# cursor = con.cursor() # カーソルの取得
return con

# Debug
if conn_f():
print("接続成功")
else:
print("接続失敗")

 

mysqlからexitする

mysql> exit

Bye

 

python db.py

↓   

接続成功

 

『接続成功』と出力されればdb.pyのコードを下記に変更

import MySQLdb

def conn_f():
con = MySQLdb.connect(
user="root",
passwd="password",
host="localhost",
db="todo_app",
charset="utf8"
)
return con

 

f:id:chocolate22554:20210419155556p:plain

 

 

=================================== 

python db.py  実行

Traceback (most recent call last):

  File "db.py", line 15, in <module>

    if conn_f():

  File "db.py", line 4, in conn_f

    con = MySQLdb.connect(

  File "/Users/((username

*2:username

*3:username

*4:username)))/opt/anaconda3/lib/python3.8/site-packages/MySQLdb/__init__.py", line 130, in Connect

    return Connection(*args, **kwargs)

  File "/Users/((username)))/opt/anaconda3/lib/python3.8/site-packages/MySQLdb/connections.py", line 185, in __init__

    super().__init__(*args, **kwargs2)

MySQLdb._exceptions.OperationalError: (2005, "Unknown MySQL server host '/tmp/mysql.sock' (0)")

(base) ((username)))@MacBook-Air2020-2 Todoアプリ %

 

which mysql_config

/usr/local/bin/mysql_config

 

f:id:chocolate22554:20210324213729p:plain

 

python db.py

Traceback (most recent call last):

  File "db.py", line 18, in <module>

    if conn_f():

  File "db.py", line 6, in conn_f

    conn_f = MySQLdb.connect(

  File "/Users/((username

*5:username

*6:username