replaced all flask references with quart references

This commit is contained in:
Philip Dowie
2020-08-15 23:27:15 +12:00
parent d23441a070
commit 2076f1c1df
21 changed files with 120 additions and 120 deletions

2
.gitignore vendored
View File

@@ -57,7 +57,7 @@ coverage.xml
local_settings.py local_settings.py
db.sqlite3 db.sqlite3
# Flask stuff: # Quart stuff:
instance/ instance/
.webassets-cache .webassets-cache

View File

@@ -1,24 +1,24 @@
# Flask-Discord # Quart-Discord
[![PyPI](https://img.shields.io/pypi/v/Flask-Discord?style=for-the-badge)](https://pypi.org/project/Flask-Discord/) [![Read the Docs](https://img.shields.io/readthedocs/flask-discord?style=for-the-badge)](https://flask-discord.readthedocs.io/en/latest/) [![Discord](https://img.shields.io/discord/690878977920729177?label=Discord%20Community&logo=Discord&style=for-the-badge)](https://discord.gg/7CrQEyP) [![PyPI](https://img.shields.io/pypi/v/Quart-Discord?style=for-the-badge)](https://pypi.org/project/Quart-Discord/) [![Read the Docs](https://img.shields.io/readthedocs/quart-discord?style=for-the-badge)](https://quart-discord.readthedocs.io/en/latest/)
Discord OAuth2 extension for Flask. Discord OAuth2 extension for Quart.
### Installation ### Installation
To install current latest release you can use following command: To install current latest release you can use following command:
```sh ```sh
python3 -m pip install Flask-Discord python3 -m pip install Quart-Discord
``` ```
### Basic Example ### Basic Example
```python ```python
from flask import Flask, redirect, url_for from quart import Quart, redirect, url_for
from flask_discord import DiscordOAuth2Session, requires_authorization, Unauthorized from quart_discord import DiscordOAuth2Session, requires_authorization, Unauthorized
app = Flask(__name__) app = Quart(__name__)
app.secret_key = b"random bytes representing flask secret key" app.secret_key = b"random bytes representing quart secret key"
app.config["DISCORD_CLIENT_ID"] = 490732332240863233 # Discord client ID. app.config["DISCORD_CLIENT_ID"] = 490732332240863233 # Discord client ID.
app.config["DISCORD_CLIENT_SECRET"] = "" # Discord client secret. app.config["DISCORD_CLIENT_SECRET"] = "" # Discord client secret.
@@ -67,7 +67,7 @@ For an example to the working application, check [`test_app.py`](tests/test_app.
### Requirements ### Requirements
* Flask * Quart
* requests_oauthlib * requests_oauthlib
* cachetools * cachetools
* discord.py * discord.py
@@ -77,4 +77,4 @@ For an example to the working application, check [`test_app.py`](tests/test_app.
Head over to [documentation] for full API reference. Head over to [documentation] for full API reference.
[documentation]: https://flask-discord.readthedocs.io/en/latest/ [documentation]: https://quart-discord.readthedocs.io/en/latest/

View File

@@ -8,11 +8,11 @@ attributes and available methods.
Discord OAuth2 Client Discord OAuth2 Client
--------------------- ---------------------
.. autoclass:: flask_discord.DiscordOAuth2Session .. autoclass:: quart_discord.DiscordOAuth2Session
:members: :members:
:inherited-members: :inherited-members:
.. autoclass:: flask_discord._http.DiscordOAuth2HttpClient .. autoclass:: quart_discord._http.DiscordOAuth2HttpClient
:members: :members:
:inherited-members: :inherited-members:
@@ -20,23 +20,23 @@ Discord OAuth2 Client
Models Models
------ ------
.. autoclass:: flask_discord.models.Guild .. autoclass:: quart_discord.models.Guild
:members: :members:
:inherited-members: :inherited-members:
.. autoclass:: flask_discord.models.User .. autoclass:: quart_discord.models.User
:members: :members:
:inherited-members: :inherited-members:
.. autoclass:: flask_discord.models.Bot .. autoclass:: quart_discord.models.Bot
:members: :members:
:inherited-members: :inherited-members:
.. autoclass:: flask_discord.models.Integration .. autoclass:: quart_discord.models.Integration
:members: :members:
:inherited-members: :inherited-members:
.. autoclass:: flask_discord.models.UserConnection .. autoclass:: quart_discord.models.UserConnection
:members: :members:
:inherited-members: :inherited-members:
@@ -44,20 +44,20 @@ Models
Utilities Utilities
--------- ---------
.. autodecorator:: flask_discord.requires_authorization .. autodecorator:: quart_discord.requires_authorization
Exceptions Exceptions
---------- ----------
.. autoclass:: flask_discord.HttpException .. autoclass:: quart_discord.HttpException
:members: :members:
.. autoclass:: flask_discord.RateLimited .. autoclass:: quart_discord.RateLimited
:members: :members:
.. autoclass:: flask_discord.Unauthorized .. autoclass:: quart_discord.Unauthorized
:members: :members:
.. autoclass:: flask_discord.AccessDenied .. autoclass:: quart_discord.AccessDenied
:members: :members:

View File

@@ -14,16 +14,16 @@ import os
import re import re
import sys import sys
sys.path.insert(0, os.path.abspath('..')) sys.path.insert(0, os.path.abspath('..'))
sys.path.append('../flask_discord/') sys.path.append('../quart_discord/')
# -- Project information ----------------------------------------------------- # -- Project information -----------------------------------------------------
project = 'Flask-Discord' project = 'Quart-Discord'
copyright = '2019, □ | The Cosmos' copyright = '2020, Philip Dowie'
author = '□ | The Cosmos' author = 'Philip Dowie'
with open('../flask_discord/__init__.py') as f: with open('../quart_discord/__init__.py') as f:
ver = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', f.read(), re.MULTILINE).group(1) ver = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', f.read(), re.MULTILINE).group(1)
# The short X.Y version # The short X.Y version
version = ver version = ver
@@ -48,7 +48,7 @@ extensions = [
intersphinx_mapping = { intersphinx_mapping = {
'python': ('https://docs.python.org/3', None), 'python': ('https://docs.python.org/3', None),
'discord': ('https://discordpy.readthedocs.io/en/latest/', None), 'discord': ('https://discordpy.readthedocs.io/en/latest/', None),
'flask': ('https://flask.palletsprojects.com/en/1.1.x/', None), 'quart': ('https://pgjones.gitlab.io/quart/', None),
'cachetools': ('https://cachetools.readthedocs.io/en/stable/', None), 'cachetools': ('https://cachetools.readthedocs.io/en/stable/', None),
'requests_oauthlib': ('https://requests-oauthlib.readthedocs.io/en/latest/', None) 'requests_oauthlib': ('https://requests-oauthlib.readthedocs.io/en/latest/', None)
} }

View File

@@ -1,14 +1,14 @@
.. Flask-Discord documentation master file, created by .. Quart-Discord documentation master file, created by
sphinx-quickstart on Wed May 8 08:29:45 2019. sphinx-quickstart on Wed May 8 08:29:45 2019.
You can adapt this file completely to your liking, but it should at least You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive. contain the root `toctree` directive.
Welcome to Flask-Discord's documentation! Welcome to Quart-Discord's documentation!
========================================= =========================================
.. image:: /images/background.jpg .. image:: /images/background.jpg
Flask-Discord is an extension made for Flask which makes implementation of Quart-Discord is an extension made for Quart which makes implementation of
Discord's OAuth2 API easier. Discord's OAuth2 API easier.
**Features** **Features**

View File

@@ -5,7 +5,7 @@
Introduction Introduction
============ ============
Flask-Discord is an extension for Flask - Python web framework which Quart-Discord is an extension for Quart - Python web framework which
makes easy implementation of Discord OAuth2 API. After creating a discord makes easy implementation of Discord OAuth2 API. After creating a discord
client object, one can easily request authorization and hence any of the client object, one can easily request authorization and hence any of the
resources provided by the discord OAuth2 API under the available scope resources provided by the discord OAuth2 API under the available scope
@@ -14,14 +14,14 @@ permissions.
Requirements Requirements
------------ ------------
- **Flask** - **Quart**
This is an Flask extension. This is a Quart extension.
- **requests_oauthlib** - **requests_oauthlib**
It also requires requests_oauthlib to make OAuth2 sessions with discord. It also requires requests_oauthlib to make OAuth2 sessions with discord.
- **cachetools** - **cachetools**
Flask Discord supports caching discord objects to boost the performance when page loads. Quart Discord supports caching discord objects to boost the performance when page loads.
- **discord.py** - **discord.py**
Makes use of discord.py for re-using many Discord models. Makes use of discord.py for re-using many Discord models.
@@ -29,15 +29,15 @@ Requirements
Installing Installing
---------- ----------
You can install Flask-Discord directly from PyPI using PIP and following command You can install Quart-Discord directly from PyPI using PIP and following command
in shell or command prompt: :: in shell or command prompt: ::
python3 -m pip install -U Flask-Discord python3 -m pip install -U Quart-Discord
You can also install the latest development version (**maybe unstable/broken**) by You can also install the latest development version (**maybe unstable/broken**) by
using following command: :: using following command: ::
python3 -m pip install -U git+https://github.com/thec0sm0s/Flask-Discord.git@dev python3 -m pip install -U git+https://github.com/jnawk/Quart-Discord.git@dev
Basic Usage Basic Usage
@@ -48,12 +48,12 @@ in exchange for fetching user's details and display them on web page.
.. code-block:: python3 .. code-block:: python3
from flask import Flask, redirect, url_for from quart import Quart, redirect, url_for
from flask_discord import DiscordOAuth2Session, requires_authorization, Unauthorized from quart_discord import DiscordOAuth2Session, requires_authorization, Unauthorized
app = Flask(__name__) app = Quart(__name__)
app.secret_key = b"random bytes representing flask secret key" app.secret_key = b"random bytes representing quart secret key"
app.config["DISCORD_CLIENT_ID"] = 490732332240863233 # Discord client ID. app.config["DISCORD_CLIENT_ID"] = 490732332240863233 # Discord client ID.
app.config["DISCORD_CLIENT_SECRET"] = "" # Discord client secret. app.config["DISCORD_CLIENT_SECRET"] = "" # Discord client secret.

View File

@@ -8,14 +8,14 @@ import abc
from . import configs from . import configs
from . import exceptions from . import exceptions
from flask import session, request from quart import session, request
from collections.abc import Mapping from collections.abc import Mapping
from requests_oauthlib import OAuth2Session from requests_oauthlib import OAuth2Session
class DiscordOAuth2HttpClient(abc.ABC): class DiscordOAuth2HttpClient(abc.ABC):
"""An OAuth2 http abstract base class providing some factory methods. """An OAuth2 http abstract base class providing some factory methods.
This class is meant to be overridden by :py:class:`flask_discord.DiscordOAuth2Session` and should not be This class is meant to be overridden by :py:class:`quart_discord.DiscordOAuth2Session` and should not be
used directly. used directly.
""" """
@@ -42,14 +42,14 @@ class DiscordOAuth2HttpClient(abc.ABC):
@property @property
def user_id(self) -> typing.Union[int, None]: def user_id(self) -> typing.Union[int, None]:
"""A property which returns Discord user ID if it exists in flask :py:attr:`flask.session` object. """A property which returns Discord user ID if it exists in quart :py:attr:`quart.session` object.
Returns Returns
------- -------
int int
The Discord user ID of current user. The Discord user ID of current user.
None None
If the user ID doesn't exists in flask :py:attr:`flask.session`. If the user ID doesn't exists in quart :py:attr:`quart.session`.
""" """
return session.get("DISCORD_USER_ID") return session.get("DISCORD_USER_ID")
@@ -130,10 +130,10 @@ class DiscordOAuth2HttpClient(abc.ABC):
Raises Raises
------ ------
flask_discord.Unauthorized quart_discord.Unauthorized
Raises :py:class:`flask_discord.Unauthorized` if current user is not authorized. Raises :py:class:`quart_discord.Unauthorized` if current user is not authorized.
flask_discord.RateLimited quart_discord.RateLimited
Raises an instance of :py:class:`flask_discord.RateLimited` if application is being rate limited by Discord. Raises an instance of :py:class:`quart_discord.RateLimited` if application is being rate limited by Discord.
""" """
route = configs.DISCORD_API_BASE_URL + route route = configs.DISCORD_API_BASE_URL + route
@@ -168,10 +168,10 @@ class DiscordOAuth2HttpClient(abc.ABC):
Raises Raises
------ ------
flask_discord.Unauthorized quart_discord.Unauthorized
Raises :py:class:`flask_discord.Unauthorized` if current user is not authorized. Raises :py:class:`quart_discord.Unauthorized` if current user is not authorized.
flask_discord.RateLimited quart_discord.RateLimited
Raises an instance of :py:class:`flask_discord.RateLimited` if application is being rate limited by Discord. Raises an instance of :py:class:`quart_discord.RateLimited` if application is being rate limited by Discord.
""" """
headers = {"Authorization": f"Bot {self.__bot_token}"} headers = {"Authorization": f"Bot {self.__bot_token}"}

View File

@@ -5,31 +5,31 @@ import discord
from . import configs, _http, models, utils, exceptions from . import configs, _http, models, utils, exceptions
from oauthlib.common import add_params_to_uri from oauthlib.common import add_params_to_uri
from flask import request, session, redirect, current_app from quart import request, session, redirect, current_app
class DiscordOAuth2Session(_http.DiscordOAuth2HttpClient): class DiscordOAuth2Session(_http.DiscordOAuth2HttpClient):
"""Main client class representing hypothetical OAuth2 session with discord. """Main client class representing hypothetical OAuth2 session with discord.
It uses Flask `session <http://flask.pocoo.org/docs/1.0/api/#flask.session>`_ local proxy object It uses Quart `session <https://pgjones.gitlab.io/quart/reference/source/quart.sessions.html#quart.sessions.Session>`_
to save state, authorization token and keeps record of users sessions across different requests. local proxy object to save state, authorization token and keeps record of users sessions across different requests.
This class inherits :py:class:`flask_discord._http.DiscordOAuth2HttpClient` class. This class inherits :py:class:`quart_discord._http.DiscordOAuth2HttpClient` class.
Parameters Parameters
---------- ----------
app : Flask app : Quart
An instance of your `flask application <http://flask.pocoo.org/docs/1.0/api/#flask.Flask>`_. An instance of your `quart application <https://pgjones.gitlab.io/quart/reference/source/quart.app.html#quart.app.Quart>`_.
client_id : int, optional client_id : int, optional
The client ID of discord application provided. Can be also set to flask config The client ID of discord application provided. Can be also set to quart config
with key ``DISCORD_CLIENT_ID``. with key ``DISCORD_CLIENT_ID``.
client_secret : str, optional client_secret : str, optional
The client secret of discord application provided. Can be also set to flask config The client secret of discord application provided. Can be also set to quart config
with key ``DISCORD_CLIENT_SECRET``. with key ``DISCORD_CLIENT_SECRET``.
redirect_uri : str, optional redirect_uri : str, optional
The default URL to use to redirect user to after authorization. Can be also set to flask config The default URL to use to redirect user to after authorization. Can be also set to quart config
with key ``DISCORD_REDIRECT_URI``. with key ``DISCORD_REDIRECT_URI``.
bot_token : str, optional bot_token : str, optional
The bot token of the application. This is required when you also need to access bot scope resources The bot token of the application. This is required when you also need to access bot scope resources
beyond the normal resources provided by the OAuth. Can be also set to flask config with beyond the normal resources provided by the OAuth. Can be also set to quart config with
key ``DISCORD_BOT_TOKEN``. key ``DISCORD_BOT_TOKEN``.
users_cache : cachetools.LFUCache, optional users_cache : cachetools.LFUCache, optional
Any dict like mapping to internally cache the authorized users. Preferably an instance of Any dict like mapping to internally cache the authorized users. Preferably an instance of
@@ -71,7 +71,7 @@ class DiscordOAuth2Session(_http.DiscordOAuth2HttpClient):
<https://discordapp.com/developers/docs/topics/oauth2#shared-resources-oauth2-scopes>`_. <https://discordapp.com/developers/docs/topics/oauth2#shared-resources-oauth2-scopes>`_.
data : dict, optional data : dict, optional
A mapping of your any custom data which you want to access after authorization grant. Use A mapping of your any custom data which you want to access after authorization grant. Use
`:py:meth:flask_discord.DiscordOAuth2Session.callback` to retrieve this data in your callback view. `:py:meth:quart_discord.DiscordOAuth2Session.callback` to retrieve this data in your callback view.
prompt : bool, optional prompt : bool, optional
Determines if the OAuth2 grant should be explicitly prompted and re-approved. Defaults to True. Determines if the OAuth2 grant should be explicitly prompted and re-approved. Defaults to True.
Specify False for implicit grant which will skip the authorization screen and redirect to redirect URI. Specify False for implicit grant which will skip the authorization screen and redirect to redirect URI.
@@ -85,7 +85,7 @@ class DiscordOAuth2Session(_http.DiscordOAuth2HttpClient):
Returns Returns
------- -------
redirect redirect
Flask redirect to discord authorization servers to complete authorization code grant process. Quart redirect to discord authorization servers to complete authorization code grant process.
""" """
scope = scope or request.args.get("scope", str()).split() or configs.DISCORD_OAUTH_DEFAULT_SCOPES scope = scope or request.args.get("scope", str()).split() or configs.DISCORD_OAUTH_DEFAULT_SCOPES
@@ -122,7 +122,7 @@ class DiscordOAuth2Session(_http.DiscordOAuth2HttpClient):
Meaning by default, it uses client side session handling. Meaning by default, it uses client side session handling.
Override this method if you want to handle the user's session server side. If this method is overridden then, Override this method if you want to handle the user's session server side. If this method is overridden then,
you must also override :py:meth:`flask_discord.DiscordOAuth2Session.get_authorization_token`. you must also override :py:meth:`quart_discord.DiscordOAuth2Session.get_authorization_token`.
""" """
session["DISCORD_OAUTH2_TOKEN"] = token session["DISCORD_OAUTH2_TOKEN"] = token
@@ -130,7 +130,7 @@ class DiscordOAuth2Session(_http.DiscordOAuth2HttpClient):
@staticmethod @staticmethod
def get_authorization_token() -> dict: def get_authorization_token() -> dict:
"""A static method which returns a dict containing Discord OAuth2 token and other secrets which was saved """A static method which returns a dict containing Discord OAuth2 token and other secrets which was saved
previously by `:py:meth:`flask_discord.DiscordOAuth2Session.save_authorization_token` from user's cookies. previously by `:py:meth:`quart_discord.DiscordOAuth2Session.save_authorization_token` from user's cookies.
You must override this method if you are implementing server side session handling. You must override this method if you are implementing server side session handling.
@@ -140,8 +140,8 @@ class DiscordOAuth2Session(_http.DiscordOAuth2HttpClient):
def callback(self): def callback(self):
"""A method which should be always called after completing authorization code grant process """A method which should be always called after completing authorization code grant process
usually in callback view. usually in callback view.
It fetches the authorization token and saves it flask It fetches the authorization token and saves it quart
`session <http://flask.pocoo.org/docs/1.0/api/#flask.session>`_ object. `session <https://pgjones.gitlab.io/quart/reference/source/quart.sessions.html#quart.sessions.Session>`_ object.
""" """
error = request.values.get("error") error = request.values.get("error")
@@ -157,10 +157,10 @@ class DiscordOAuth2Session(_http.DiscordOAuth2HttpClient):
return jwt.decode(state, current_app.config["SECRET_KEY"]) return jwt.decode(state, current_app.config["SECRET_KEY"])
def revoke(self): def revoke(self):
"""This method clears current discord token, state and all session data from flask """This method clears current discord token, state and all session data from quart
`session <http://flask.pocoo.org/docs/1.0/api/#flask.session>`_. Which means user will have `session <https://pgjones.gitlab.io/quart/reference/source/quart.sessions.html#quart.sessions.Session>`_. Which
to go through discord authorization token grant flow again. Also tries to remove the user from internal means user will have to go through discord authorization token grant flow again. Also tries to remove the user
cache if they exist. from internal cache if they exist.
""" """
@@ -183,7 +183,7 @@ class DiscordOAuth2Session(_http.DiscordOAuth2HttpClient):
Returns Returns
------- -------
flask_discord.models.User quart_discord.models.User
""" """
return models.User.get_from_cache() or models.User.fetch_from_api() return models.User.get_from_cache() or models.User.fetch_from_api()
@@ -196,7 +196,7 @@ class DiscordOAuth2Session(_http.DiscordOAuth2HttpClient):
Returns Returns
------- -------
list list
List of :py:class:`flask_discord.models.UserConnection` objects. List of :py:class:`quart_discord.models.UserConnection` objects.
""" """
user = models.User.get_from_cache() user = models.User.get_from_cache()
@@ -216,7 +216,7 @@ class DiscordOAuth2Session(_http.DiscordOAuth2HttpClient):
Returns Returns
------- -------
list list
List of :py:class:`flask_discord.models.Guild` objects. List of :py:class:`quart_discord.models.Guild` objects.
""" """
user = models.User.get_from_cache() user = models.User.get_from_cache()

View File

@@ -1,4 +1,4 @@
from flask import current_app from quart import current_app
from abc import ABCMeta, abstractmethod from abc import ABCMeta, abstractmethod
@@ -23,15 +23,15 @@ class DiscordModelsBase(metaclass=DiscordModelsMeta):
@staticmethod @staticmethod
def _request(*args, **kwargs): def _request(*args, **kwargs):
"""A shorthand to :py:func:flask_discord.request`. It uses Flask current_app local proxy to get the """A shorthand to :py:func:quart_discord.request`. It uses Quart current_app local proxy to get the
Flask-Discord client. Quart-Discord client.
""" """
return current_app.discord.request(*args, **kwargs) return current_app.discord.request(*args, **kwargs)
@staticmethod @staticmethod
def _bot_request(*args, **kwargs): def _bot_request(*args, **kwargs):
"""A shorthand to :py:func:flask_discord.bot_request`.""" """A shorthand to :py:func:quart_discord.bot_request`."""
return current_app.discord.bot_request(*args, **kwargs) return current_app.discord.bot_request(*args, **kwargs)
@classmethod @classmethod

View File

@@ -1,4 +1,4 @@
from flask import current_app from quart import current_app
from .base import DiscordModelsBase from .base import DiscordModelsBase
from .integration import Integration from .integration import Integration
@@ -59,19 +59,19 @@ class UserConnection(DiscordModelsBase):
@classmethod @classmethod
def fetch_from_api(cls, cache=True): def fetch_from_api(cls, cache=True):
"""A class method which returns an instance or list of instances of this model by implicitly making an """A class method which returns an instance or list of instances of this model by implicitly making an
API call to Discord. If an instance of :py:class:`flask_discord.User` exists in the users internal cache API call to Discord. If an instance of :py:class:`quart_discord.User` exists in the users internal cache
who are attached to these connections then, the cached property :py:attr:`flask_discord.User.connections` who are attached to these connections then, the cached property :py:attr:`quart_discord.User.connections`
is updated. is updated.
Parameters Parameters
---------- ----------
cache : bool cache : bool
Determines if the :py:attr:`flask_discord.User.guilds` cache should be updated with the new guilds. Determines if the :py:attr:`quart_discord.User.guilds` cache should be updated with the new guilds.
Returns Returns
------- -------
list[flask_discord.UserConnection, ...] list[quart_discord.UserConnection, ...]
List of instances of :py:class:`flask_discord.UserConnection` to which this user belongs. List of instances of :py:class:`quart_discord.UserConnection` to which this user belongs.
""" """
connections = super().fetch_from_api() connections = super().fetch_from_api()

View File

@@ -1,5 +1,5 @@
from .base import DiscordModelsBase from .base import DiscordModelsBase
from flask import current_app from quart import current_app
import discord import discord
from .. import configs from .. import configs
@@ -68,18 +68,18 @@ class Guild(DiscordModelsBase):
@classmethod @classmethod
def fetch_from_api(cls, cache=True): def fetch_from_api(cls, cache=True):
"""A class method which returns an instance or list of instances of this model by implicitly making an """A class method which returns an instance or list of instances of this model by implicitly making an
API call to Discord. If an instance of :py:class:`flask_discord.User` exists in the users internal cache API call to Discord. If an instance of :py:class:`quart_discord.User` exists in the users internal cache
who belongs to these guilds then, the cached property :py:attr:`flask_discord.User.guilds` is updated. who belongs to these guilds then, the cached property :py:attr:`quart_discord.User.guilds` is updated.
Parameters Parameters
---------- ----------
cache : bool cache : bool
Determines if the :py:attr:`flask_discord.User.guilds` cache should be updated with the new guilds. Determines if the :py:attr:`quart_discord.User.guilds` cache should be updated with the new guilds.
Returns Returns
------- -------
list[flask_discord.Guild, ...] list[quart_discord.Guild, ...]
List of instances of :py:class:`flask_discord.Guild` to which this user belongs. List of instances of :py:class:`quart_discord.Guild` to which this user belongs.
""" """
guilds = super().fetch_from_api() guilds = super().fetch_from_api()

View File

@@ -5,7 +5,7 @@ from .. import exceptions
from .base import DiscordModelsBase from .base import DiscordModelsBase
from .connections import UserConnection from .connections import UserConnection
from flask import current_app, session from quart import current_app, session
class User(DiscordModelsBase): class User(DiscordModelsBase):
@@ -48,7 +48,7 @@ class User(DiscordModelsBase):
An integer representing the An integer representing the
`type of nitro subscription <https://discordapp.com/developers/docs/resources/user#user-object-premium-types>`_. `type of nitro subscription <https://discordapp.com/developers/docs/resources/user#user-object-premium-types>`_.
connections : list connections : list
A list of :py:class:`flask_discord.UserConnection` instances. These are cached and this list might be empty. A list of :py:class:`quart_discord.UserConnection` instances. These are cached and this list might be empty.
""" """
@@ -69,12 +69,12 @@ class User(DiscordModelsBase):
self.premium_type = self._payload.get("premium_type") self.premium_type = self._payload.get("premium_type")
# Few properties which are intended to be cached. # Few properties which are intended to be cached.
self._guilds = None # Mapping of guild ID to flask_discord.models.Guild(...). self._guilds = None # Mapping of guild ID to quart_discord.models.Guild(...).
self.connections = None # List of flask_discord.models.UserConnection(...). self.connections = None # List of quart_discord.models.UserConnection(...).
@property @property
def guilds(self): def guilds(self):
"""A cached mapping of user's guild ID to :py:class:`flask_discord.Guild`. The guilds are cached when the first """A cached mapping of user's guild ID to :py:class:`quart_discord.Guild`. The guilds are cached when the first
API call for guilds is requested so it might be an empty dict. API call for guilds is requested so it might be an empty dict.
""" """
@@ -133,10 +133,10 @@ class User(DiscordModelsBase):
---------- ----------
guilds : bool guilds : bool
A boolean indicating if user's guilds should be cached or not. Defaults to ``False``. If chose to not A boolean indicating if user's guilds should be cached or not. Defaults to ``False``. If chose to not
cache, user's guilds can always be obtained from :py:func:`flask_discord.Guilds.fetch_from_api()`. cache, user's guilds can always be obtained from :py:func:`quart_discord.Guilds.fetch_from_api()`.
connections : bool connections : bool
A boolean indicating if user's connections should be cached or not. Defaults to ``False``. If chose to not A boolean indicating if user's connections should be cached or not. Defaults to ``False``. If chose to not
cache, user's connections can always be obtained from :py:func:`flask_discord.Connections.fetch_from_api()`. cache, user's connections can always be obtained from :py:func:`quart_discord.Connections.fetch_from_api()`.
Returns Returns
------- -------
@@ -161,7 +161,7 @@ class User(DiscordModelsBase):
Returns Returns
------- -------
flask_discord.User quart_discord.User
An user instance if it exists in internal cache. An user instance if it exists in internal cache.
None None
If the current doesn't exists in internal cache. If the current doesn't exists in internal cache.
@@ -184,8 +184,8 @@ class User(DiscordModelsBase):
Raises Raises
------ ------
flask_discord.Unauthorized quart_discord.Unauthorized
Raises :py:class:`flask_discord.Unauthorized` if current user is not authorized. Raises :py:class:`quart_discord.Unauthorized` if current user is not authorized.
""" """
try: try:
@@ -201,7 +201,7 @@ class User(DiscordModelsBase):
Returns Returns
------- -------
list list
List of :py:class:`flask_discord.Guilds` instances. List of :py:class:`quart_discord.Guilds` instances.
""" """
self._guilds = {guild.id: guild for guild in Guild.fetch_from_api(cache=False)} self._guilds = {guild.id: guild for guild in Guild.fetch_from_api(cache=False)}
@@ -214,7 +214,7 @@ class User(DiscordModelsBase):
Returns Returns
------- -------
list list
A list of :py:class:`flask_discord.UserConnection` instances. A list of :py:class:`quart_discord.UserConnection` instances.
""" """
self.connections = UserConnection.fetch_from_api(cache=False) self.connections = UserConnection.fetch_from_api(cache=False)

View File

@@ -3,7 +3,7 @@
import functools import functools
from . import exceptions from . import exceptions
from flask import current_app from quart import current_app
class JSONBool(object): class JSONBool(object):
@@ -35,7 +35,7 @@ def json_bool(value):
# Decorators. # Decorators.
def requires_authorization(view): def requires_authorization(view):
"""A decorator for flask views which raises exception :py:class:`flask_discord.Unauthorized` if the user """A decorator for quart views which raises exception :py:class:`quart_discord.Unauthorized` if the user
is not authorized from Discord OAuth2. is not authorized from Discord OAuth2.
""" """

View File

@@ -1,4 +1,4 @@
Flask Quart
pyjwt pyjwt
requests requests
oauthlib oauthlib

View File

@@ -1,8 +1,8 @@
""" """
Flask-Discord Quart-Discord
------------- -------------
An Discord OAuth2 flask extension. An Discord OAuth2 quart extension.
""" """
import re import re
@@ -12,12 +12,12 @@ from setuptools import setup, find_packages
def __get_version(): def __get_version():
with open("flask_discord/__init__.py") as package_init_file: with open("quart_discord/__init__.py") as package_init_file:
return re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', package_init_file.read(), re.MULTILINE).group(1) return re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', package_init_file.read(), re.MULTILINE).group(1)
requirements = [ requirements = [
'Flask', 'Quart',
'pyjwt', 'pyjwt',
'oauthlib', 'oauthlib',
'requests_oauthlib', 'requests_oauthlib',
@@ -40,13 +40,13 @@ extra_requirements = {
setup( setup(
name='Flask-Discord', name='Quart-Discord',
version=__get_version(), version=__get_version(),
url='https://github.com/thec0sm0s/Flask-Discord', url='https://github.com/quart/Quart-Discord',
license='MIT', license='MIT',
author='□ | The Cosmos', author='□ | The Cosmos',
author_email='deepakrajko14@gmail.com', author_email='deepakrajko14@gmail.com',
description='Discord OAuth2 extension for Flask.', description='Discord OAuth2 extension for Quart.',
long_description=__doc__, long_description=__doc__,
packages=find_packages(), packages=find_packages(),
zip_safe=False, zip_safe=False,
@@ -55,7 +55,7 @@ setup(
install_requires=requirements, install_requires=requirements,
extra_requirements=extra_requirements, extra_requirements=extra_requirements,
classifiers=[ classifiers=[
'Framework :: Flask', 'Framework :: Quart',
'Environment :: Web Environment', 'Environment :: Web Environment',
'Intended Audience :: Developers', 'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License', 'License :: OSI Approved :: MIT License',

View File

@@ -1,10 +1,10 @@
import os import os
from flask import Flask, redirect, url_for from quart import Quart, redirect, url_for
from flask_discord import DiscordOAuth2Session, requires_authorization from quart_discord import DiscordOAuth2Session, requires_authorization
app = Flask(__name__) app = Quart(__name__)
app.secret_key = b"%\xe0'\x01\xdeH\x8e\x85m|\xb3\xffCN\xc9g" app.secret_key = b"%\xe0'\x01\xdeH\x8e\x85m|\xb3\xffCN\xc9g"