メインコンテンツまでスキップ

Python Development Setup, pyenv, uv

· 約2分
Mikyan
白い柴犬

This article introduce how to setup python development environment for Web development.

For data science / machine learning development environment, you might prefer other approaches, like anaconda.

Details

Install uv​

US is the modern solution and handles both Python versions AND package management. It's like having nvm + npm in one tool.

curl -LsSf https://astral.sh/uv/install.sh | sh

source $HOME/.local/bin/env

Use uv

# Install uv
curl -LsSf https://astral.sh/uv/install.sh | sh

# Install and use Python
uv python install 3.12
uv python pin 3.12 # Sets Python version for project

Use uv to initialize the project​

cd my-project

uv init --python 3.12

Then the following files are generated:

tree
├── main.py
├── pyproject.toml
└── README.md

pyproject.toml is just like package.json

Initialize venv:

% uv venv
Using CPython 3.12.11
Creating virtual environment at: .venv
Activate with: source .venv/bin/activate
% source .venv/bin/activate

You can use venv in this project now.

# install deps
# it automatically use venv
uv sync

# add new package
uv add fastapi sqlalchemy alembic

Check the pyproject.toml file's

If want to init a fastapi project, using fastapi's template here might be a better choice.

git clone [email protected]:fastapi/full-stack-fastapi-template.git my-full-stack
cd my-full-stack
git remote set-url origin [email protected]:octocat/my-full-stack.git
git push -u origin master

Git Cheat Sheet

· 約6分
Mikyan
白い柴犬

問題の背景​

チームで開発する際、よくあるパターンとして、

  • developブランチから、featureブランチAを切って実装、PullRequestを作成し、レビュー待ち
  • その間に、featureブランチAにfeatureブランチBを切って、新しい機能を実装します
  • featureブランチAのレビューを経て承認され、スカッシュマージによってdevelopブランチへ統合され
  • この時、featureブランチBのコミットがfeatureブランチAの元のコミットに含まれてしまうことがあって、developブランチと多くのマージコンフリクトが発生してしまいました。

問題発生の原因​

  • スカッシュマージによって個々のコミットがまとめられたため、ブランチBには依然としてブランチAの個々の変更が残っていること
  • その結果、developブランチに既に存在するスカッシュコミットとブランチBの変更が重複して適用され、コンフリクトが発生したこと

解決策:リベースによる解決​

ブランチBをブランチA由来のコミットを取り除いて、developブランチ上のスカッシュコミットに合わせてリベースすることで、効率よく解決できます。

具体的には、以下の手順で行います:

git checkout feature/branch-b
git rebase --onto develop HASH_BASE feature/branch-b

このコマンドは、ブランチ B の中で HASH_BASE より後のコミットだけを、develop ブランチ上に再適用します。 HASH_BASEは、ブランチ A が develop から分岐した時点のコミットハッシュにすると、元ブランチ A のコミットがブランチ B に含まれなくなります。

リベース中にコンフリクトが発生した場合、各コンフリクト箇所で適切に修正し、 以下のコマンドでリベースを続行します。

git add <修正済みファイル>
git rebase --continue

リベースが正常に完了したら、ブランチ B の変更を develop ブランチへPRを作成してマージしましょう。

この方法により、履歴がクリーンになり、将来的なマージやデバッグ作業が大幅に楽になります。

Remote ブランチにコミットしました

問題の背景​

リモートブランチをLocalにFetchせずに、チェックアウトし、

git checkout origin/branch-a

をすると、そのまま作業し、コミットしたら、プッシュできない。下記のエラーメッセージ表示されました:

error: src refspec feature/branch does not match any
error: failed to push some refs to 'github.com:organization/project.git'

問題発生の原因​

Fetchが忘れて、RemoteブランチをCheckoutするとき、実際のHEADはそのブランチではなく、detached HEADの状態です。 すると、ブランチに所属せず、特定のコミットを指している状態です。

git checkout origin/main
# または
git checkout <コミットID>
HEAD → origin/main の最新コミットを直接指す(ローカルブランチではない)

ブランチは指していない
→ この状態でコミットすると、その履歴はどのブランチにも属しません。

そのまま作業して、コミットできるか、そのコミットはブランチ属していない、浮いた状態です。 git log, git reflogで確認できますが、後で消える可能性がある あくまで一時的な作業や、過去のコミットを試す時に使うモード

解決策​

  1. ブランチからそのコミットハッシュをcherry-pickしたら解決
git log
# copy the コミット hash abc1234
git checkout branch
git cherry-pick abc1234
git push origin branch
  1. このコミットから新しいブランチを作成で解決
git branch feature/tmp abc1234

リベースの後で--force-with-leaseでプッシュ​

git rebaseの後、--force でプッシュが必要でしょう。 このとき、--force-with-leaseでプッシュするとより安全にプッシュできます。

git push --force-with-lease

すべてのCommitを一つにする

GitHubで他の人が作ったボイラープレートをクローンして、自分のプロジェクトを始めることはよくあります。しかし、元のコミット履歴は不要なので、削除したほうがよいでしょう。 以下の手順でクリーンなリポジトリを作成できます:

方法1: 履歴のない新しいブランチを作成

# Navigate to your repository
cd your-repo

# Create a new orphan branch (no commit history)
git checkout --orphan clean-master

# Add all files
git add -A

# Create the first commit
git commit -m "Initial commit"

# Delete the old master branch
git branch -D master

# Rename the current branch to master
git branch -m master

# Force push to your remote repository
git push -f origin master

方法2: .gitフォルダを削除して再初期化

# Navigate to your repository
cd your-repo

# Remove the .git folder (this deletes all history)
rm -rf .git

# Initialize a new repository
git init

# Add all files
git add -A

# Create the first commit
git commit -m "Initial commit"

# Add your remote repository
git remote add origin https://github.com/yourusername/your-repo.git

# Push to your repository
git push -u origin master

google-analtyics-add-custom-properties

· 約1分
  • Setting deviceId as a user property via gtag('set', 'user_properties', {'deviceId': deviceId}); means it will be associated with all subsequent events, including automatic ones. This is generally the recommended way to handle persistent user-level identifiers.

The custom_map in the config call within ClientTrackingInitializer (window.gtag('config', GA_TRACKING_ID, {'custom_map': {'dimension1': 'deviceId'}})) is used to map an event parameter or user property named deviceId to a custom dimension (in this case, dimension1) in your GA4 reports. For this to effectively map a user property, the custom dimension in

GA4 should be user-scoped.

Why this setup should generally work for your goal:

When gtag('set', 'user_properties', {'deviceId': deviceId}) is called, any events fired after this (including automatic page_view events if this set happens before the config that triggers them, or subsequent page_view events on SPA navigations) will have this user property associated.

User properties are automatically sent with events to GA4.

意思決定の全てはROI

· 約2分
Mikyan
白い柴犬

複数人が関わっているプロジェクトのやり方、難易度はグッと上がるです。 なぜなら、人々のコミュニケーション、すり合わせ、タスク間の依存関係、を考えなければならないです。しかもこれらのプロジェクトのインパクトが高い、できれば大きな利益が出る、うまくできないと大きな損失が出る可能性があるのできちんと管理する必要があります。

チームでのプロジェクトの進め方は、個人プロジェクトの管理方法に加えて、以下三つの要点があります:

  • プロジェクトを分解をする
    • MECEで分解
    • 前後依頼を確定
  • 各タスクを関与する人を確定、評価するかどうかを確定
  • 各マイルストーンの確認時点を定める

プロジェクト管理についての理解1、一人プロジェクト

· 約5分
Mikyan
白い柴犬

これまでいくつかの会社で、さまざまなプロジェクトの管理やリードに関わってきました。
その中で得た知見を、将来の自分のためにも簡単にまとめておきたいと思います。

プロジェクトとは、「限られたリソースを使い、限られた期間で、特定の目的を達成する取り組み」です。
その目的を実現するためには、適切な管理が欠かせません。

プロジェクトの規模によって管理方法は大きく異なるため、私は以下の3つに分類できると考えています。

  • 一人プロジェクト
  • チームプロジェクト
  • 複数組織が関わるプロジェクト

今回はこの中でも、「一人プロジェクト」の管理についてまとめてみます。


一人プロジェクトとは?

プロジェクトの定義を広く捉えれば、さまざまな取り組みがプロジェクトとして扱えます。
たとえば、以下のようなものも一人プロジェクトに該当します。

  • 個人旅行の計画
  • ブログの運営
  • 上司に依頼された勉強会の企画

一人で進めるプロジェクトは、特に管理が軽視されがちです。
単なるタスクのように感覚的に進めてしまうことも多いでしょう。

しかし、「これはプロジェクトだ」と意識し、適切に管理することで、より楽しく、より良い結果を得ることができます。


一人プロジェクト管理で意識すべき3つのポイント

1. 目的を明確にする​

  • 「なぜそれをやるのか?」を繰り返し問いかけ、問題を言語化します。
  • 曖昧なまま進めると、途中で迷子になったり、やり直しが発生したりします。

特に他人から頼まれたプロジェクトでは、目的が明確にされていないことが多いです。

例:勉強会の幹事を任された場合​

  • チームのコミュニケーションを活性化するため?
  • AIなど最先端技術を学ぶ場として?
  • プレゼン能力を伸ばすため?
  • チームカルチャーを育てるため?

目的によって、トピック選定、参加メンバー、運営方針がすべて変わってきます。
だからこそ、最初に目的を明確にすることが最重要です。


2. マイルストーンに分解する​

  • タスクが小さく見えても、実際は難しい部分や不確実な要素が隠れていることがあります。
  • あらかじめ全体像を把握し、マイルストーン(節目)に分解しておくことで、計画的に進めることができます。

また、マイルストーンは進捗の報告タイミングとしても活用できます。


3. 報連相(報告・連絡・相談)を怠らない​

一人で進めるからこそ、「見える化」が重要です。
上司や依頼者に対して、今どこまで進んでいるか・どんな課題があるかを適切に共有しましょう。

これには以下のメリットがあります:

  • 認識違いがあっても、早い段階で軌道修正できる
  • 環境や要件の変化にも柔軟に対応できる
  • 自分の成果が評価されやすくなる

おわりに

一人で動くプロジェクトこそ、意識的に「プロジェクト」として扱うことで成果が変わってきます。

  • 目的の明確化
  • マイルストーンの設計
  • 可視化と報連相

この3つを意識すれば、小さな取り組みでも効果的に、そして気持ちよく進めることができるでしょう。

Redis

· 約1分
Mikyan
白い柴犬

一文でRedisの機能やユースケースをまとめてみる。

Redis とは

Redisは様々なデータ構造に対応したインメモリデータストアです。

具体的に言うと、下記のデータ構造を対応しています:

  • Strings (simple binary-safe blobs)
  • Lists (linked lists, with operations like LPUSH, LRANGE, etc.)
  • Hashes (maps/dictionaries of field→value pairs)
  • Sets (unordered collections of unique elements)
  • Sorted Sets (elements ordered by a score, i.e. your “sorted array”)
  • Bitmaps (compact bit arrays)
  • HyperLogLogs (probabilistic cardinality counters)
  • Streams (append-only log data structures)
  • Geospatial indexes (store and query latitude/longitude points)

データ構造の対応ではなくて、便利な操作機能も提供しており、普段のデータベースで実装しにくい機能を簡単に実装できます。

How to setup SFTP in EC2 allowing file upload

· 約2分
Mikyan
白い柴犬

SFTP use SSH protocal, allowing user to transfer files safely. It is a subsystem of SSH, so it runs in port 22.

The name contains FTP, however it is not implements FTP protocal

  • It achieves the same function with FTP
  • It is widely supported by FTP clients

When you want to transfer files with server, it might be a good choice.

How to setup a sftp user allowing it to upload files into specific folder

The following scripts helps setup a SFTP user in

Save it to .sh file, execute the following commands

chmod +x setup_sftp_user.sh
sudo ./setup_sftp_user.sh vendor

It will prompt you to set the password and configure the rest automatically.

#!/bin/bash

# Check if running as root
if [ "$EUID" -ne 0 ]; then
echo "Please run as root or use sudo"
exit 1
fi

# Check if username is provided
if [ -z "$1" ]; then
echo "Usage: $0 <username>"
exit 1
fi

USER=$1

# Create user
useradd -m $USER
passwd $USER

# Setup SFTP directories
mkdir -p /var/sftp/$USER/uploads
chown root:root /var/sftp/$USER
chmod 755 /var/sftp/$USER

chown $USER:$USER /var/sftp/$USER/uploads
chmod 755 /var/sftp/$USER/uploads

# Backup sshd_config
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak

# Add SSH config for user
cat <<EOL >> /etc/ssh/sshd_config

Match User $USER
ChrootDirectory /var/sftp/$USER
ForceCommand internal-sftp
AllowTcpForwarding no
X11Forwarding no
EOL

# Restart SSH daemon
systemctl restart sshd

# Confirm success
echo "SFTP user '$USER' has been set up successfully."

Best Practice

· 約1分
Mikyan
白い柴犬

To simplify & unify the system logic, the following convention are considered as best practice:

  • Store everything in UTC
  • Use UTC everywhere in backend
  • Use UTC, with ISO-8601 format in API layer
  • Frontend: Convert to user's local time