This repository has been archived by the owner on Dec 11, 2021. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1
Migrate off topic channel name endpoint from the site API #26
Closed
Shivansh-007
wants to merge
5
commits into
python-discord:main
from
Shivansh-007:migrate/otn-endpoint
Closed
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
8de0793
Migrate reminders endpoint from the site API
D0rs4n 3d2a265
Patch test workflow
D0rs4n 8b9cf92
Remove the need to specify a Database URL in the test workflow
D0rs4n cfb6e87
Migrate off topic channel name endpoint from the site API
Shivansh-007 fd1dc9d
Inherit unittest.Testcase and use unittest assert methods
Shivansh-007 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
from api.core.database import session_factory | ||
|
||
|
||
def create_database_session() -> None: | ||
"""A FastAPI dependency that creates an SQLAlchemy session.""" | ||
db = session_factory() | ||
try: | ||
yield db | ||
finally: | ||
db.close() |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,142 @@ | ||
from typing import Optional, Union | ||
|
||
from fastapi import APIRouter, Depends | ||
from fastapi.responses import JSONResponse | ||
from sqlalchemy.orm import Query, Session | ||
|
||
from api.core.database.models.api.bot import OffTopicChannelName | ||
from api.core.schemas import ErrorMessage | ||
from api.endpoints.dependencies.database import create_database_session | ||
|
||
otn = APIRouter(prefix="/off-topic-channel-names") | ||
|
||
|
||
def get_all_otn(db_session: Session) -> Query: | ||
"""Get a partial query object with .all().""" | ||
return db_session.query(OffTopicChannelName).all() | ||
|
||
|
||
@otn.get( | ||
"/", | ||
status_code=200, | ||
response_model=list[str], | ||
D0rs4n marked this conversation as resolved.
Show resolved
Hide resolved
|
||
responses={404: {"model": ErrorMessage}}, | ||
) | ||
def get_off_topic_channel_names( | ||
random_items: Optional[int] = None, | ||
db_session: Session = Depends(create_database_session), | ||
) -> Union[JSONResponse, list[str]]: | ||
""" | ||
### GET /bot/off-topic-channel-names. | ||
|
||
Return all known off-topic channel names from the database. | ||
|
||
If the `random_items` query parameter is given, for example using... | ||
$ curl 127.0.0.1:8000/api/bot/off-topic-channel-names?random_items=5 | ||
... then the API will return `5` random items from the database | ||
that is not used in current rotation. | ||
|
||
When running out of names, API will mark all names to not used and start new rotation. | ||
|
||
#### Response format | ||
Return a list of off-topic-channel names: | ||
>>> [ | ||
... "lemons-lemonade-stand", | ||
... "bbq-with-bisk" | ||
... ] | ||
|
||
#### Status codes | ||
- 200: returned on success | ||
- 400: returned when `random_items` is not a positive integer | ||
|
||
## Authentication | ||
Requires a API token. | ||
""" | ||
if not random_items: | ||
queryset = get_all_otn(db_session) | ||
return [offtopic_name.name for offtopic_name in queryset] | ||
Shivansh-007 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
if random_items <= 0: | ||
return JSONResponse( | ||
status_code=404, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. According to the API "docs": |
||
content={"error": ["'random_items' must be a positive integer."]}, | ||
) | ||
|
||
queryset = get_all_otn(db_session).order_by("used", "?")[:random_items] | ||
|
||
# When any name is used in our listing then this means we reached end of round | ||
# and we need to reset all other names `used` to False | ||
if any(offtopic_name.used for offtopic_name in queryset): | ||
# These names that we just got have to be excluded from updating used to False | ||
get_all_otn(db_session).update( | ||
{ | ||
OffTopicChannelName.used: OffTopicChannelName.name | ||
in (offtopic_name.name for offtopic_name in queryset) | ||
} | ||
) | ||
else: | ||
# Otherwise mark selected names `used` to True | ||
get_all_otn(db_session).filter_by( | ||
name__in=(offtopic_name.name for offtopic_name in queryset) | ||
).update(used=True) | ||
|
||
return [offtopic_name.name for offtopic_name in queryset] | ||
|
||
|
||
@otn.post( | ||
"/", | ||
status_code=201, | ||
responses={400: {"model": ErrorMessage}}, | ||
) | ||
def create_off_topic_channel_names( | ||
name: str, | ||
db_session: Session = Depends(create_database_session), | ||
) -> None: | ||
""" | ||
### POST /bot/off-topic-channel-names. | ||
|
||
Create a new off-topic-channel name in the database. | ||
The name must be given as a query parameter, for example: | ||
$ curl 127.0.0.1:8000/api/bot/off-topic-channel-names?name=lemons-lemonade-shop | ||
|
||
#### Status codes | ||
- 201: returned on success | ||
- 400: if the request body has invalid fields, see the response for details | ||
|
||
## Authentication | ||
Requires a API token. | ||
""" | ||
new_off_topic_channel_name = OffTopicChannelName(name=name) | ||
db_session.add(new_off_topic_channel_name) | ||
db_session.commit() | ||
|
||
|
||
@otn.delete("/", status_code=204, responses={404: {"model": ErrorMessage}}) | ||
async def delete_off_topic_channel_names( | ||
name: str, db_session: Session = Depends(create_database_session) | ||
) -> Optional[JSONResponse]: | ||
""" | ||
### DELETE /bot/off-topic-channel-names/<name:str>. | ||
|
||
Delete the off-topic-channel name with the given `name`. | ||
|
||
#### Status codes | ||
- 204: returned on success | ||
- 404: returned when the given `name` was not found | ||
|
||
## Authentication | ||
Requires a API token. | ||
""" | ||
if not ( | ||
otn_to_delete := db_session.query(OffTopicChannelName) | ||
.filter_by(name=name) | ||
.first() | ||
): | ||
return JSONResponse( | ||
status_code=404, | ||
content={ | ||
"error": "There is no off topic channel name with that `name` in the database" | ||
}, | ||
) | ||
db_session.delete(otn_to_delete) | ||
db_session.commit() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
from .reminder_endpoints import reminder |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
from fastapi import Depends | ||
|
||
from .reminder_schemas import ReminderFilter | ||
|
||
|
||
async def filter_values(reminder_filter: ReminderFilter = Depends()) -> dict: | ||
"""Returns a dictionary exported from a ReminderFilter model from the Path, with None values excluded.""" | ||
return reminder_filter.dict(exclude_none=True) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Could you move this to a separate file, into something like
otn_dependency
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It isn't really a dependency and is only used in the current file, I don't think it deserves to go in a separate dependency file.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If your code depends on this function, then it is a dependency, the reason I ask is because in the future new dependencies could be added, and I believe it would make the project structure more friendly.