[개발이야기#041] 내가 해보고 싶은 것 - 한국 스팀잇 M2E 사용자 모임 글 수집하기 - 사용자 등록
안녕하세요 가야태자 @talkit 입니다.
관련글
[개발이야기#028] 내가 해보고 싶은 것 - 자동 보팅 프로그램 SQLite vs DuckDB [postingcuration]
[개발이야기#029] 내가 해보고 싶은 것 - 자동 보팅 프로그램 사용자 및 포스트 테이블 생성하기 [postingcuration]
[개발이야기#031] 내가 해보고 싶은 것 - 자동 보팅 프로그램 사용자 등록 프로그램 작성하기 [postingcuration]
[개발이야기#032] 내가 해보고 싶은 것 - 자동 보팅 프로그램 사용자 게시글 수집기 작성하기 [postingcuration]
[개발이야기#034] 내가 해보고 싶은 것 - 포스팅 큐레이션 글을 자동으로 정리해보자 [postingcuration]
[개발이야기#034] 내가 해보고 싶은 것 - 포스팅 큐레이션 글 목록을 자동 포스팅 하기 [postingcuration]
[개발이야기#035] 내가 해보고 싶은 것 - 자동 보팅 프로그램 하루에 한번 보팅하는 프로그램[postingcuration]\
[개발이야기#036] 내가 해보고 싶은 것 - 자동 보팅 프로그램 스케쥴러 프로그램 [postingcuration]
[개발이야기#037] 내가 해보고 싶은 것 - 자동 보팅 프로그램 정리 [postingcuration]
[개발이야기#040] 내가 해보고 싶은 것 - 한국 스팀잇 M2E 사용자 모임 글 수집하기
머릿말
이번 글은 지난 번 글에서 이어서 사용자를 관리 하는 프로그램을 짜보겠습니다.
이번에도 지난 번과 같은 도스 프로그램을 작성 합니다.
도스 프로그램으로 프로토 타입을 작성하고, 추후에 해당 내용을 웹으로 구현 예정입니다.
이 때도 디비를 마이라디비로 변경한게 많은 도움이 될 것으로 생각 됩니다.^^
사용자 등록 프로그램 코드
import mariadb
import sys
class UserManagerCLI:
def __init__(self, host, user, password, database):
"""Initialize the connection to the MariaDB database."""
try:
self.connection = mariadb.connect(
host=host,
user=user,
password=password,
database=database
)
self.cursor = self.connection.cursor()
print("Connected to MariaDB database")
except mariadb.Error as e:
print(f"Error while connecting to MariaDB: {e}")
sys.exit(1)
def add_user(self, user_id, nickname=None, is_active='Y', registered_at=None):
"""Add a new user to the users table."""
try:
query = """
INSERT INTO users (user_id, nickname, is_active, registered_at, modified_at)
VALUES (?, ?, ?, ?, ?)
"""
self.cursor.execute(query, (user_id, nickname, is_active, registered_at, registered_at))
self.connection.commit()
print("User added successfully!")
except mariadb.Error as e:
print(f"Failed to add user: {e}")
def update_user(self, user_id, nickname=None, is_active=None, modified_at=None):
"""Update a user's details."""
try:
query = "UPDATE users SET "
updates = []
values = []
if nickname:
updates.append("nickname = ?")
values.append(nickname)
if is_active:
updates.append("is_active = ?")
values.append(is_active)
if modified_at:
updates.append("modified_at = ?")
values.append(modified_at)
if updates:
query += ", ".join(updates) + " WHERE user_id = ?"
values.append(user_id)
self.cursor.execute(query, values)
self.connection.commit()
print("User updated successfully!")
else:
print("No updates made.")
except mariadb.Error as e:
print(f"Failed to update user: {e}")
def delete_user(self, user_id):
"""Delete a user from the users table."""
try:
query = "DELETE FROM users WHERE user_id = ?"
self.cursor.execute(query, (user_id,))
self.connection.commit()
print("User deleted successfully!")
except mariadb.Error as e:
print(f"Failed to delete user: {e}")
def list_users(self):
"""List all users."""
try:
query = "SELECT * FROM users"
self.cursor.execute(query)
rows = self.cursor.fetchall()
if rows:
print("User List:")
for row in rows:
print(row)
else:
print("No users found.")
except mariadb.Error as e:
print(f"Failed to retrieve users: {e}")
def __del__(self):
"""Close the connection when the object is deleted."""
if self.connection:
self.cursor.close()
self.connection.close()
print("MariaDB connection closed.")
def main():
manager = UserManagerCLI(host='localhost', user='root', password='yourpassword', database='yourdatabase')
while True:
print("\nUser Management CLI")
print("1. Add User")
print("2. Update User")
print("3. Delete User")
print("4. List Users")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == "1":
user_id = input("Enter user ID: ")
nickname = input("Enter nickname (optional): ")
registered_at = input("Enter registered date (YYYY-MM-DD): ")
manager.add_user(user_id, nickname, registered_at=registered_at)
elif choice == "2":
user_id = input("Enter user ID to update: ")
nickname = input("Enter new nickname (optional): ")
is_active = input("Enter active status (Y/N, optional): ")
modified_at = input("Enter modified date (YYYY-MM-DD): ")
manager.update_user(user_id, nickname, is_active, modified_at)
elif choice == "3":
user_id = input("Enter user ID to delete: ")
manager.delete_user(user_id)
elif choice == "4":
manager.list_users()
elif choice == "5":
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
가상 환경 생성
conda create -n steemitm2e python=3.12
아나콘다에서 위 명령어을 입력하면, 새로운 가상 환경이 생성 됩니다.
conda activate steemitm2e
위 명령어로 steemitm2e 가상환경을 사용할 수 있습니다.
conda deactivate
위 명령어로 가상환경을 해제 할 수 있습니다.
프로그램 파일 저장
user_management_mysql.py
저는 위 파일명으로 저장 했습니다.
마리아 디비 패키지 설치
pip install mariadb
코드 일부 수정
manager = UserManagerCLI(host='localhost', user='root', password='yourpassword', database='yourdatabase')
위 코드는 수정 하셔야 합니다.
저는 아래와 같이 수정 했습니다.
manager = UserManagerCLI(host='마리아디비서버아이피', user='사용자명', password='비밀번호', database='steemit_postings')
위와 같이 변경 해주었습니다. 여러분의 환경에 맞게 수정 하셔야 합니다.
MariaDB 사용자 생성 및 권한 부여여
-- steemit 사용자 생성 (192.168.0.% 대역에서 접속 가능)
CREATE USER 'steemit'@'192.168.0.%' IDENTIFIED BY '비밀번호';
-- steemit_postings 데이터베이스의 모든 권한 부여
GRANT ALL PRIVILEGES ON steemit_postings.* TO 'steemit'@'192.168.0.%';
-- 권한 적용
FLUSH PRIVILEGES;
저기서 비밀번호는 적당히 변경하기고 따라 하시면 될 것 같습니다.
manager = UserManagerCLI(host='마리아디비서버아이피', user='steemit', password='비밀번호', database='steemit_postings')
이제 위코드 처럼 변경 할 수 있습니다. 비밀번호는 적당히 주시구요 비밀번호를 변경해주시면 됩니다.
코드 사용하기
python user_management_mysql.py
위와 같이 사용하면 됩니다.
사용법은 DuckDB 용하고 동일 합니다.
프로그램 상에 날짜를 입력하는 부분은 그냥 그날 날자를 넣어 주시면 됩니다.
혹시나 등록일이 다르면 수정 하셔서 넣어주십시오.
User Management CLI
1. Add User
2. Update User
3. Delete User
4. List Users
5. Exit
Enter your choice: 4
User List:
('happypray', 'happypray', 'Y', datetime.date(2024, 10, 26), datetime.date(2024, 10, 26))
('jungjunghoon', 'jungjunghoon', 'Y', datetime.date(2024, 10, 26), datetime.date(2024, 10, 26))
('mantonge', 'mantonge', 'Y', datetime.date(2024, 10, 26), datetime.date(2024, 10, 26))
('parkname', 'parkname', 'Y', datetime.date(2024, 10, 26), datetime.date(2024, 10, 26))
('talkit', 'talkit', 'Y', datetime.date(2024, 10, 26), datetime.date(2024, 10, 26))
대략 위와 같은 모양의 포그램 입니다. ^^
맺음말
오늘은 여기까지 하고, 다음 프로그램에서 steemit 글을 수집하는 프로그램을 MySQL용으로 변경 해보겠습니다.
감사합니다.
Posted through the ECblog app (https://blog.etain.club)
[광고] STEEM 개발자 커뮤니티에 참여 하시면, 다양한 혜택을 받을 수 있습니다.