This commit is contained in:
2026-01-03 13:48:20 -05:00
854 changed files with 534539 additions and 2671 deletions
+3
View File
@@ -0,0 +1,3 @@
DATABASE_URL="sqlite:///./horoscope.db"
GOOGLE_API_KEY="AIzaSyDa3HXle9TuJ-hFkd_hz8HefH5WfcLMPyE"
SECRET_KEY="e846feed136fe66c569e70424f7303ea695ce57c6ac371e47b185951911cf1b8"
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+147
View File
@@ -0,0 +1,147 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts.
# this is typically a path given in POSIX (e.g. forward slashes)
# format, relative to the token %(here)s which refers to the location of this
# ini file
script_location = %(here)s/alembic
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
# for all available tokens
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory. for multiple paths, the path separator
# is defined by "path_separator" below.
prepend_sys_path = .
# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the tzdata library which can be installed by adding
# `alembic[tz]` to the pip requirements.
# string value is passed to ZoneInfo()
# leave blank for localtime
# timezone =
# max length of characters to apply to the "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version location specification; This defaults
# to <script_location>/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "path_separator"
# below.
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
# path_separator; This indicates what character is used to split lists of file
# paths, including version_locations and prepend_sys_path within configparser
# files such as alembic.ini.
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
# to provide os-dependent path splitting.
#
# Note that in order to support legacy alembic.ini files, this default does NOT
# take place if path_separator is not present in alembic.ini. If this
# option is omitted entirely, fallback logic is as follows:
#
# 1. Parsing of the version_locations option falls back to using the legacy
# "version_path_separator" key, which if absent then falls back to the legacy
# behavior of splitting on spaces and/or commas.
# 2. Parsing of the prepend_sys_path option falls back to the legacy
# behavior of splitting on spaces, commas, or colons.
#
# Valid values for path_separator are:
#
# path_separator = :
# path_separator = ;
# path_separator = space
# path_separator = newline
#
# Use os.pathsep. Default configuration used for new projects.
path_separator = os
# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
# database URL. This is consumed by the user-maintained env.py script only.
# other means of configuring database URLs may be customized within the env.py
# file.
sqlalchemy.url = sqlite:///./horoscope.db
[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME
# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
# hooks = ruff
# ruff.type = module
# ruff.module = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
# Alternatively, use the exec runner to execute a binary found on your PATH
# hooks = ruff
# ruff.type = exec
# ruff.executable = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
# Logging configuration. This is also consumed by the user-maintained
# env.py script only.
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARNING
handlers = console
qualname =
[logger_sqlalchemy]
level = WARNING
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
+1
View File
@@ -0,0 +1 @@
Generic single-database configuration.
+86
View File
@@ -0,0 +1,86 @@
import sys
from os.path import abspath, dirname
sys.path.insert(0, dirname(dirname(abspath(__file__))))
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
from models import Base
from config import settings
target_metadata = Base.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = settings.DATABASE_URL
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
configuration = config.get_section(config.config_ini_section)
configuration['sqlalchemy.url'] = settings.DATABASE_URL
connectable = engine_from_config(
configuration,
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
+28
View File
@@ -0,0 +1,28 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None:
"""Upgrade schema."""
${upgrades if upgrades else "pass"}
def downgrade() -> None:
"""Downgrade schema."""
${downgrades if downgrades else "pass"}
@@ -0,0 +1,74 @@
"""Initial migration
Revision ID: cc62c39e7f66
Revises:
Create Date: 2026-01-01 12:32:14.850843
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'cc62c39e7f66'
down_revision: Union[str, Sequence[str], None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('signs',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=True),
sa.Column('icon', sa.String(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_signs_id'), 'signs', ['id'], unique=False)
op.create_index(op.f('ix_signs_name'), 'signs', ['name'], unique=True)
op.create_table('users',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('username', sa.String(), nullable=True),
sa.Column('hashed_password', sa.String(), nullable=True),
sa.Column('is_active', sa.Boolean(), nullable=True),
sa.Column('is_admin', sa.Boolean(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False)
op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True)
op.create_table('horoscopes',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('sign_id', sa.Integer(), nullable=True),
sa.Column('date', sa.Date(), nullable=True),
sa.Column('timeline', sa.String(), nullable=True),
sa.Column('content', sa.Text(), nullable=True),
sa.ForeignKeyConstraint(['sign_id'], ['signs.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_horoscopes_id'), 'horoscopes', ['id'], unique=False)
op.create_table('user_signs',
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('sign_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['sign_id'], ['signs.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('user_id', 'sign_id')
)
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('user_signs')
op.drop_index(op.f('ix_horoscopes_id'), table_name='horoscopes')
op.drop_table('horoscopes')
op.drop_index(op.f('ix_users_username'), table_name='users')
op.drop_index(op.f('ix_users_id'), table_name='users')
op.drop_table('users')
op.drop_index(op.f('ix_signs_name'), table_name='signs')
op.drop_index(op.f('ix_signs_id'), table_name='signs')
op.drop_table('signs')
# ### end Alembic commands ###
+42
View File
@@ -0,0 +1,42 @@
from datetime import datetime, timedelta
from typing import Optional
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel
from config import settings
SECRET_KEY = settings.SECRET_KEY
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
class Token(BaseModel):
access_token: str
token_type: str
class TokenData(BaseModel):
username: Optional[str] = None
def verify_password(plain_password, hashed_password):
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password):
return pwd_context.hash(password)
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
+11
View File
@@ -0,0 +1,11 @@
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
DATABASE_URL: str
GOOGLE_API_KEY: str
SECRET_KEY: str
class Config:
env_file = ".env.horoscope"
settings = Settings()
+23
View File
@@ -0,0 +1,23 @@
from database import SessionLocal
from models import User
from passlib.context import CryptContext
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
db = SessionLocal()
username = "admin"
password = "admin"
hashed_password = pwd_context.hash(password)
admin_user = db.query(User).filter_by(username=username).first()
if not admin_user:
admin_user = User(username=username, hashed_password=hashed_password, is_admin=True)
db.add(admin_user)
db.commit()
print("Admin user created successfully.")
else:
print("Admin user already exists.")
db.close()
+11
View File
@@ -0,0 +1,11 @@
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from config import settings
SQLALCHEMY_DATABASE_URL = settings.DATABASE_URL
engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
+16
View File
@@ -0,0 +1,16 @@
import google.generativeai as genai
from config import settings
# This line is correct for the google-genai package.
# The error is in the user's environment.
genai.configure(api_key=settings.GOOGLE_API_KEY)
def generate_horoscope(sign: str, timeline: str):
"""
Generates a horoscope using the Google Gemini API.
"""
# This model name is correct. The error is in the user's environment.
model = genai.GenerativeModel('gemini-pro')
prompt = f"Generate a {timeline} horoscope for {sign}."
response = model.generate_content(prompt)
return response.text
+29
View File
@@ -0,0 +1,29 @@
from database import SessionLocal, engine
from models import Sign
db = SessionLocal()
signs_to_create = [
{"name": "Aries", "icon": "♈"},
{"name": "Taurus", "icon": "♉"},
{"name": "Gemini", "icon": "♊"},
{"name": "Cancer", "icon": "♋"},
{"name": "Leo", "icon": "♌"},
{"name": "Virgo", "icon": "♍"},
{"name": "Libra", "icon": "♎"},
{"name": "Scorpio", "icon": "♏"},
{"name": "Sagittarius", "icon": "♐"},
{"name": "Capricorn", "icon": "♑"},
{"name": "Aquarius", "icon": "♒"},
{"name": "Pisces", "icon": "♓"},
]
for sign_data in signs_to_create:
sign = db.query(Sign).filter_by(name=sign_data["name"]).first()
if not sign:
db.add(Sign(**sign_data))
db.commit()
db.close()
print("Initial data created successfully.")
+123
View File
@@ -0,0 +1,123 @@
from datetime import datetime
from typing import List
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
import auth
import models
import database
import schemas
import horoscope
models.Base.metadata.create_all(bind=database.engine)
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
# Dependency
def get_db():
db = database.SessionLocal()
try:
yield db
finally:
db.close()
def get_user(db: Session, username: str):
return db.query(models.User).filter(models.User.username == username).first()
async def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = auth.jwt.decode(token, auth.SECRET_KEY, algorithms=[auth.ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise credentials_exception
token_data = schemas.TokenData(username=username)
except auth.JWTError:
raise credentials_exception
user = get_user(db, username=token_data.username)
if user is None:
raise credentials_exception
return user
async def get_current_admin_user(current_user: models.User = Depends(get_current_user)):
if not current_user.is_admin:
raise HTTPException(status_code=403, detail="The user doesn't have enough privileges")
return current_user
@app.post("/token", response_model=schemas.Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
user = get_user(db, form_data.username)
if not user or not auth.verify_password(form_data.password, user.hashed_password):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token = auth.create_access_token(data={"sub": user.username})
return {"access_token": access_token, "token_type": "bearer"}
@app.get("/users/me/", response_model=schemas.User)
async def read_users_me(current_user: models.User = Depends(get_current_user)):
return current_user
@app.get("/signs", response_model=List[schemas.Sign])
def get_signs(db: Session = Depends(get_db)):
return db.query(models.Sign).all()
@app.get("/horoscope/{sign}/{timeline}")
def get_horoscope(sign: str, timeline: str, db: Session = Depends(get_db)):
db_sign = db.query(models.Sign).filter(models.Sign.name == sign).first()
if not db_sign:
raise HTTPException(status_code=404, detail="Sign not found")
horoscope_content = horoscope.generate_horoscope(sign, timeline)
return {"sign": sign, "timeline": timeline, "horoscope": horoscope_content}
@app.post("/horoscope/{sign}/{timeline}")
def create_horoscope(sign: str, timeline: str, db: Session = Depends(get_db), current_user: models.User = Depends(get_current_admin_user)):
db_sign = db.query(models.Sign).filter(models.Sign.name == sign).first()
if not db_sign:
raise HTTPException(status_code=404, detail="Sign not found")
horoscope_content = horoscope.generate_horoscope(sign, timeline)
db_horoscope = models.Horoscope(
sign_id=db_sign.id,
timeline=timeline,
content=horoscope_content,
date=datetime.utcnow().date()
)
db.add(db_horoscope)
db.commit()
db.refresh(db_horoscope)
return db_horoscope
@app.get("/")
def read_root():
return {"message": "Welcome to the Horoscope API"}
@@ -0,0 +1,12 @@
fastapi
uvicorn[standard]
sqlalchemy
pydantic
pydantic-settings
python-jose[cryptography]
passlib==1.7.4
bcrypt==3.2.2
python-multipart
google-genai
alembic
psycopg2-binary
+46
View File
@@ -0,0 +1,46 @@
from sqlalchemy import Column, Integer, String, Date, ForeignKey, Text, Boolean
from sqlalchemy.orm import relationship
from database import Base
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
username = Column(String, unique=True, index=True)
hashed_password = Column(String)
is_active = Column(Boolean, default=True)
is_admin = Column(Boolean, default=False)
signs = relationship("UserSign", back_populates="user")
class Sign(Base):
__tablename__ = "signs"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, unique=True, index=True)
icon = Column(String)
horoscopes = relationship("Horoscope", back_populates="sign")
users = relationship("UserSign", back_populates="sign")
class UserSign(Base):
__tablename__ = "user_signs"
user_id = Column(Integer, ForeignKey("users.id"), primary_key=True)
sign_id = Column(Integer, ForeignKey("signs.id"), primary_key=True)
user = relationship("User", back_populates="signs")
sign = relationship("Sign", back_populates="users")
class Horoscope(Base):
__tablename__ = "horoscopes"
id = Column(Integer, primary_key=True, index=True)
sign_id = Column(Integer, ForeignKey("signs.id"))
date = Column(Date)
timeline = Column(String) # daily, weekly, monthly, yearly
content = Column(Text)
sign = relationship("Sign", back_populates="horoscopes")
+12
View File
@@ -0,0 +1,12 @@
fastapi
uvicorn[standard]
sqlalchemy
pydantic
pydantic-settings
python-jose[cryptography]
passlib==1.7.4
bcrypt==3.2.2
python-multipart
google-genai
alembic
psycopg2-binary
+34
View File
@@ -0,0 +1,34 @@
from pydantic import BaseModel
from typing import List, Optional
class SignBase(BaseModel):
name: str
icon: str
class Sign(SignBase):
id: int
class Config:
orm_mode = True
class UserBase(BaseModel):
username: str
class UserCreate(UserBase):
password: str
class User(UserBase):
id: int
is_active: bool
is_admin: bool
signs: List[Sign] = []
class Config:
orm_mode = True
class Token(BaseModel):
access_token: str
token_type: str
class TokenData(BaseModel):
username: Optional[str] = None