repo
stringclasses
856 values
pull_number
int64
3
127k
instance_id
stringlengths
12
58
issue_numbers
sequencelengths
1
5
base_commit
stringlengths
40
40
patch
stringlengths
67
1.54M
test_patch
stringlengths
0
107M
problem_statement
stringlengths
3
307k
hints_text
stringlengths
0
908k
created_at
timestamp[s]
ckan/ckan
7,359
ckan__ckan-7359
[ "7358" ]
978875e41643b53fc2c714b2264f32e502db3f8d
diff --git a/ckanext/datastore/backend/postgres.py b/ckanext/datastore/backend/postgres.py --- a/ckanext/datastore/backend/postgres.py +++ b/ckanext/datastore/backend/postgres.py @@ -1142,6 +1142,8 @@ def upsert_data(context: Context, data_dict: dict[str, Any]): if value is not None and field['type'].lower() == 'nested': # a tuple with an empty second value value = (json.dumps(value), '') + elif value == '' and field['type'] != 'text': + value = None row.append(value) rows.append(row) @@ -1187,6 +1189,8 @@ def upsert_data(context: Context, data_dict: dict[str, Any]): if value is not None and field['type'].lower() == 'nested': # a tuple with an empty second value record[field['id']] = (json.dumps(value), '') + elif value == '' and field['type'] != 'text': + record[field['id']] = None non_existing_field_names = [ field for field in record
diff --git a/ckanext/datastore/tests/test_upsert.py b/ckanext/datastore/tests/test_upsert.py --- a/ckanext/datastore/tests/test_upsert.py +++ b/ckanext/datastore/tests/test_upsert.py @@ -613,6 +613,38 @@ def test_id_instead_of_pk_update(self): assert search_result["records"][0]["book"] == "The boy" assert search_result["records"][0]["author"] == "F Torres" + @pytest.mark.ckan_config("ckan.plugins", "datastore") + @pytest.mark.usefixtures("clean_datastore", "with_plugins") + def test_empty_string_instead_of_null(self): + resource = factories.Resource() + data = { + "resource_id": resource["id"], + "force": True, + "primary_key": "pk", + "fields": [ + {"id": "pk", "type": "text"}, + {"id": "n", "type": "int"}, + {"id": "d", "type": "date"}, + ], + "records": [{"pk": "1000", "n": "5", "d": "2020-02-02"}], + } + helpers.call_action("datastore_create", **data) + + data = { + "resource_id": resource["id"], + "force": True, + "method": "upsert", + "records": [ + {"pk": "1000", "n": "", "d": ""} + ], + } + helpers.call_action("datastore_upsert", **data) + + search_result = _search(resource["id"]) + assert search_result["total"] == 1 + rec = search_result["records"][0] + assert rec == {'_id': 1, 'pk': '1000', 'n': None, 'd': None} + @pytest.mark.usefixtures("with_request_context") class TestDatastoreInsert(object): @@ -719,6 +751,37 @@ def test_key_already_exists(self): context.value ) + @pytest.mark.ckan_config("ckan.plugins", "datastore") + @pytest.mark.usefixtures("clean_datastore", "with_plugins") + def test_empty_string_instead_of_null(self): + resource = factories.Resource() + data = { + "resource_id": resource["id"], + "force": True, + "primary_key": "pk", + "fields": [ + {"id": "pk", "type": "text"}, + {"id": "n", "type": "int"}, + {"id": "d", "type": "date"}, + ], + } + helpers.call_action("datastore_create", **data) + + data = { + "resource_id": resource["id"], + "force": True, + "method": "insert", + "records": [ + {"pk": "1000", "n": "", "d": ""} + ], + } + helpers.call_action("datastore_upsert", **data) + + search_result = _search(resource["id"]) + assert search_result["total"] == 1 + rec = search_result["records"][0] + assert rec == {'_id': 1, 'pk': '1000', 'n': None, 'd': None} + @pytest.mark.usefixtures("with_request_context") class TestDatastoreUpdate(object): @@ -951,3 +1014,35 @@ def test_id_instead_of_pk_update(self): assert search_result["records"][0]["pk"] == "1000" assert search_result["records"][0]["book"] == "The boy" assert search_result["records"][0]["author"] == "F Torres" + + @pytest.mark.ckan_config("ckan.plugins", "datastore") + @pytest.mark.usefixtures("clean_datastore", "with_plugins") + def test_empty_string_instead_of_null(self): + resource = factories.Resource() + data = { + "resource_id": resource["id"], + "force": True, + "primary_key": "pk", + "fields": [ + {"id": "pk", "type": "text"}, + {"id": "n", "type": "int"}, + {"id": "d", "type": "date"}, + ], + "records": [{"pk": "1000", "n": "5", "d": "2020-02-02"}], + } + helpers.call_action("datastore_create", **data) + + data = { + "resource_id": resource["id"], + "force": True, + "method": "update", + "records": [ + {"pk": "1000", "n": "", "d": ""} + ], + } + helpers.call_action("datastore_upsert", **data) + + search_result = _search(resource["id"]) + assert search_result["total"] == 1 + rec = search_result["records"][0] + assert rec == {'_id': 1, 'pk': '1000', 'n': None, 'd': None}
lenient datastore_upsert ## CKAN version master ## Describe the bug passing an empty value for a date or other numeric field could store null in the field instead of raising an error ### Steps to reproduce upsert `''` as a value to a datetime, numeric, etc. datastore field ### Expected behavior not cause a db error ### Additional details
2023-01-25T21:04:47
ckan/ckan
7,371
ckan__ckan-7371
[ "6449" ]
2a05d13ede56d64345916e8dc3b033a69aab56d3
diff --git a/ckan/config/environment.py b/ckan/config/environment.py --- a/ckan/config/environment.py +++ b/ckan/config/environment.py @@ -9,7 +9,7 @@ from typing import Union, cast -import sqlalchemy +from sqlalchemy import engine_from_config, inspect import sqlalchemy.exc import ckan.model as model @@ -220,7 +220,7 @@ def update_config() -> None: # to eliminate database errors due to stale pooled connections config.setdefault('sqlalchemy.pool_pre_ping', True) # Initialize SQLAlchemy - engine = sqlalchemy.engine_from_config(config) + engine = engine_from_config(config) model.init_model(engine) for plugin in p.PluginImplementations(p.IConfigurable): @@ -232,14 +232,18 @@ def update_config() -> None: authz.clear_auth_functions_cache() # Here we create the site user if they are not already in the database + user_table_exists = False try: - logic.get_action('get_site_user')({'ignore_auth': True}, {}) - except (sqlalchemy.exc.ProgrammingError, sqlalchemy.exc.OperationalError): - # The database is not yet initialised. It happens in `ckan db init` - pass - except sqlalchemy.exc.IntegrityError: - # Race condition, user already exists. - pass + user_table_exists = inspect(engine).has_table("user") + except sqlalchemy.exc.OperationalError: + log.debug("DB user table does not exist") + + if user_table_exists: + try: + logic.get_action('get_site_user')({'ignore_auth': True}, {}) + except sqlalchemy.exc.IntegrityError: + # Race condition, user already exists. + log.debug("Site user already exists") # Close current session and open database connections to ensure a clean # clean environment even if an error occurs later on diff --git a/ckan/model/__init__.py b/ckan/model/__init__.py --- a/ckan/model/__init__.py +++ b/ckan/model/__init__.py @@ -8,8 +8,7 @@ from time import sleep from typing import Any, Optional -from sqlalchemy import MetaData, Table -from sqlalchemy.exc import ProgrammingError +from sqlalchemy import MetaData, Table, inspect from alembic.command import ( upgrade as alembic_upgrade, @@ -278,12 +277,13 @@ def setup_migration_version_control(self) -> None: alembic_config.set_main_option( "sqlalchemy.url", config.get("sqlalchemy.url") ) - try: + + sqlalchemy_migrate_version = 0 + db_inspect = inspect(self.metadata.bind) + if db_inspect.has_table("migrate_version"): sqlalchemy_migrate_version = self.metadata.bind.execute( u'select version from migrate_version' ).scalar() - except ProgrammingError: - sqlalchemy_migrate_version = 0 # this value is used for graceful upgrade from # sqlalchemy-migrate to alembic
Failures when initializing the database **CKAN version** 2.9.4 **Describe the bug** First run: ``` ckan | 2021-10-01 10:39:30,892 INFO [ckan.config.environment] Loading templates from /usr/lib/ckan/venv/src/ckan/ckan/templates db | 2021-10-01 10:39:30.906 UTC [118] ERROR: relation "user" does not exist at character 515 db | 2021-10-01 10:39:30.906 UTC [118] STATEMENT: SELECT "user".password AS user_password, "user".id AS user_id, "user".name AS user_name, "user".fullname AS user_fullname, "user".email AS user_email, "user".apikey AS user_apikey, "user".created AS user_created, "user".reset_key AS user_reset_key, "user".about AS user_about, "user".activity_streams_email_notifications AS user_activity_streams_email_notifications, "user".sysadmin AS user_sysadmin, "user".state AS user_state, "user".image_url AS user_image_url, "user".plugin_extras AS user_plugin_extras db | FROM "user" db | WHERE "user".name = 'default' OR "user".id = 'default' ORDER BY "user".name db | LIMIT 1 ckan | 2021-10-01 10:39:32,945 INFO [ckan.cli.db] Initialize the Database db | 2021-10-01 10:39:32.946 UTC [119] ERROR: relation "migrate_version" does not exist at character 21 db | 2021-10-01 10:39:32.946 UTC [119] STATEMENT: select version from migrate_version ckan | 2021-10-01 10:39:35,534 INFO [ckan.model] CKAN database version upgraded: base -> ccd38ad5fced (head) ckan | 2021-10-01 10:39:35,534 INFO [ckan.model] Database initialised ckan | Initialising DB: SUCCESS ``` Second run: ``` ckan | 2021-10-01 10:41:26,508 INFO [ckan.cli.db] Initialize the Database db | 2021-10-01 10:41:26.509 UTC [37] ERROR: relation "migrate_version" does not exist at character 21 db | 2021-10-01 10:41:26.509 UTC [37] STATEMENT: select version from migrate_version ckan | 2021-10-01 10:41:26,625 INFO [ckan.model] CKAN database version remains as: ccd38ad5fced (head) ckan | 2021-10-01 10:41:26,625 INFO [ckan.model] Database initialised ckan | Initialising DB: SUCCESS ``` **Steps to reproduce** Steps to reproduce the behavior: `docker-compose up; docker-compose down; docker-compose up` **Expected behavior** No errors. **Additional details** Docker is used.
For what it's worth Iv'e seen this error for a while now...for me (and my simple testing) it seems benign but I'm not sure....this will get discussed in next Tuesday's Dev meeting It does not seem to affect CKAN, but it would be nice to avoid having it, as log monitoring tools will always see an "ERROR" popping up from time to time. Thanks! :) These are benign, but if someone wants to try to suppress them they should review the Docker entrypoint scripts to see what commands are emitting and try to figure out why there are being shown. This one `ERROR: relation "migrate_version" does not exist at character 21` is being generated [here](https://github.com/ckan/ckan/blob/a226a70019d850683ac77abe5a9df9bde2c2f0a4/ckan/model/__init__.py#L266) when we are checking if the old versioning system is present.
2023-02-01T15:14:44
ckan/ckan
7,387
ckan__ckan-7387
[ "7386" ]
640abe63ca90ff890f14d3ce2654e4402bb39ba6
diff --git a/ckanext/datastore/helpers.py b/ckanext/datastore/helpers.py --- a/ckanext/datastore/helpers.py +++ b/ckanext/datastore/helpers.py @@ -206,9 +206,13 @@ def _get_subquery_from_crosstab_call(ct: str): return ct.replace("''", "'") -def datastore_dictionary(resource_id: str): +def datastore_dictionary( + resource_id: str, include_columns: Optional[list[str]] = None): """ - Return the data dictionary info for a resource + Return the data dictionary info for a resource, optionally filtering + columns returned. + + include_columns is a list of column ids to include in the output """ try: return [ @@ -217,6 +221,8 @@ def datastore_dictionary(resource_id: str): u'resource_id': resource_id, u'limit': 0, u'include_total': False})['fields'] - if not f['id'].startswith(u'_')] + if not f['id'].startswith(u'_') and ( + include_columns is None or f['id'] in include_columns) + ] except (tk.ObjectNotFound, tk.NotAuthorized): return []
datatablesview: show columns feature bug ## CKAN version master, 2.10 (earlier?) ## Describe the bug If any columns are unselected when creating a view, the view will not appear. ### Steps to reproduce When creating or editing a datatablesview (not viewing an existing one) un-check some columns and save the view. ### Expected behavior Those columns should be excluded but view should still work. ### Additional details
2023-02-09T20:31:21
ckan/ckan
7,424
ckan__ckan-7424
[ "7411" ]
a4b3fbff4479c062dc4e3d3e7a9b7d640f933a69
diff --git a/ckan/lib/app_globals.py b/ckan/lib/app_globals.py --- a/ckan/lib/app_globals.py +++ b/ckan/lib/app_globals.py @@ -7,6 +7,7 @@ import re from threading import Lock from typing import Any, Union +from packaging.version import parse as parse_version import ckan import ckan.model as model @@ -14,6 +15,7 @@ from ckan.common import asbool, config, aslist + log = logging.getLogger(__name__) @@ -219,11 +221,12 @@ def _check_uptodate(self): def _init(self): self.ckan_version = ckan.__version__ - self.ckan_base_version = re.sub(r'[^0-9\.]', '', self.ckan_version) - if self.ckan_base_version == self.ckan_version: - self.ckan_doc_version = self.ckan_version[:3] + version = parse_version(self.ckan_version) + self.ckan_base_version = version.base_version + if not version.is_prerelease: + self.ckan_doc_version = f"{version.major}.{version.minor}" else: - self.ckan_doc_version = 'latest' + self.ckan_doc_version = "latest" # process the config details to set globals for key in app_globals_from_config_details.keys(): new_key, value = process_app_global(key, config.get(key) or '')
2.10.0 - Link to CKAN-API in footer points to 404 ## CKAN version 2.10.0 ## Describe the bug CKAN-API link in the footer points to 404 site: http://docs.ckan.org/en/2.1/api/ ![ckan_api_404](https://user-images.githubusercontent.com/414984/220368786-68cac0db-552c-4265-b65a-9f4e73cfd8c3.png) ### Steps to reproduce See/Click the CKAN-API link in the footer. ### Expected behavior Landing on a working site with details about the CKAN-API, probably: https://docs.ckan.org/en/2.10/api/ ### Additional details *
2023-03-04T06:28:16
ckan/ckan
7,436
ckan__ckan-7436
[ "6708" ]
8c1ee7b62c2c03c283aa1b01afce48a4c2f2eda2
diff --git a/ckan/common.py b/ckan/common.py --- a/ckan/common.py +++ b/ckan/common.py @@ -68,14 +68,14 @@ def streaming_response(data: Iterable[Any], def ugettext(*args: Any, **kwargs: Any) -> str: - return cast(str, flask_ugettext(*args, **kwargs)) + return flask_ugettext(*args, **kwargs) _ = ugettext def ungettext(*args: Any, **kwargs: Any) -> str: - return cast(str, flask_ungettext(*args, **kwargs)) + return flask_ungettext(*args, **kwargs) class CKANConfig(MutableMapping): diff --git a/ckan/config/middleware/flask_app.py b/ckan/config/middleware/flask_app.py --- a/ckan/config/middleware/flask_app.py +++ b/ckan/config/middleware/flask_app.py @@ -10,7 +10,7 @@ import logging from logging.handlers import SMTPHandler -from typing import Any, Iterable, Optional, Union, cast +from typing import Any, Optional, Union, cast from flask import Blueprint, send_from_directory, current_app from flask.ctx import _AppCtxGlobals @@ -82,33 +82,6 @@ def __call__(self, environ: Any, start_response: Any): return self.app(environ, start_response) -class CKANBabel(Babel): - app: CKANApp - - def __init__(self, *pargs: Any, **kwargs: Any): - super(CKANBabel, self).__init__(*pargs, **kwargs) - self._i18n_path_idx = 0 - - @property - def domain(self) -> str: - default = super(CKANBabel, self).domain - multiple = self.app.config.get('BABEL_MULTIPLE_DOMAINS') - if not multiple: - return default - domains = multiple.split(';') - try: - return domains[self._i18n_path_idx] - except IndexError: - return default - - @property - def translation_directories(self) -> Iterable[str]: - self._i18n_path_idx = 0 - for path in super(CKANBabel, self).translation_directories: - yield path - self._i18n_path_idx += 1 - - def _ungettext_alias(): u''' Provide `ungettext` as an alias of `ngettext` for backwards @@ -246,13 +219,10 @@ def make_flask_stack(conf: Union[Config, CKANConfig]) -> CKANApp: i18n_dirs, i18n_domains = zip(*pairs) app.config[u'BABEL_TRANSLATION_DIRECTORIES'] = ';'.join(i18n_dirs) - app.config[u'BABEL_DOMAIN'] = 'ckan' - app.config[u'BABEL_MULTIPLE_DOMAINS'] = ';'.join(i18n_domains) + app.config[u'BABEL_DOMAIN'] = ';'.join(i18n_domains) app.config[u'BABEL_DEFAULT_TIMEZONE'] = str(h.get_display_timezone()) - babel = CKANBabel(app) - - babel.localeselector(get_locale) + Babel(app, locale_selector=get_locale) # WebAssets _setup_webassets(app) diff --git a/ckan/lib/i18n.py b/ckan/lib/i18n.py --- a/ckan/lib/i18n.py +++ b/ckan/lib/i18n.py @@ -46,7 +46,7 @@ import six from babel import Locale -from babel.core import (LOCALE_ALIASES, # type: ignore +from babel.core import (LOCALE_ALIASES, get_locale_identifier, UnknownLocaleError) import polib
diff --git a/ckan/tests/controllers/test_package.py b/ckan/tests/controllers/test_package.py --- a/ckan/tests/controllers/test_package.py +++ b/ckan/tests/controllers/test_package.py @@ -2,6 +2,7 @@ from bs4 import BeautifulSoup from werkzeug.routing import BuildError +from flask_babel import refresh as refresh_babel import unittest.mock as mock import ckan.authz as authz @@ -89,6 +90,8 @@ def test_change_locale(self, app, user): url = url_for("dataset.new") env = {"Authorization": user["token"]} res = app.get(url, extra_environ=env) + # See https://github.com/python-babel/flask-babel/issues/214 + refresh_babel() res = app.get("/de/dataset/new", extra_environ=env) assert helpers.body_contains(res, "Datensatz") diff --git a/ckan/tests/lib/test_formatters.py b/ckan/tests/lib/test_formatters.py --- a/ckan/tests/lib/test_formatters.py +++ b/ckan/tests/lib/test_formatters.py @@ -58,7 +58,7 @@ class TestLocalizedNiceDate(object): (_now, False, False, False, u"Just now"), (_now, True, False, False, u"October 23, 2017"), (_now, True, True, False, u"October 23, 2017, 16:03 (UTC)"), - (_now, True, True, True, u"October 23, 2017 at 4:03:52 PM UTC"), + (_now, True, True, True, u"October 23, 2017, 4:03:52\u202fPM UTC"), (_now, False, True, True, u"Just now"), (_now, False, False, True, u"Just now"), (_now, False, True, False, u"Just now"), @@ -97,7 +97,7 @@ def test_relative_dates(self, dt, expected): (_now, False, False, u"MMM, YY", u"Oct, 17"), (_now, True, False, None, u"October 23, 2017, 16:03 (UTC)"), (_now, True, False, u"EEE, HH:mm", u"Mon, 16:03"), - (_now, True, True, None, u"October 23, 2017 at 4:03:52 PM UTC"), + (_now, True, True, None, u"October 23, 2017, 4:03:52\u202fPM UTC"), ( _now, True, diff --git a/ckan/tests/lib/test_helpers.py b/ckan/tests/lib/test_helpers.py --- a/ckan/tests/lib/test_helpers.py +++ b/ckan/tests/lib/test_helpers.py @@ -495,7 +495,7 @@ def test_named_timezone(self): ( datetime.datetime(2008, 4, 13, 20, 40, 59, 123456), {"with_seconds": True}, - "April 13, 2008 at 8:40:59 PM UTC", + "April 13, 2008, 8:40:59\u202fPM UTC", ), ("2008-04-13T20:40:20.123456", {}, "April 13, 2008"), (None, {}, ""), diff --git a/ckanext/activity/tests/test_helpers.py b/ckanext/activity/tests/test_helpers.py --- a/ckanext/activity/tests/test_helpers.py +++ b/ckanext/activity/tests/test_helpers.py @@ -21,8 +21,7 @@ def test_simple(self): html = out[0] assert ( str(html) - == '<option value="id1" >February 1, 2018 at 10:58:59 AM UTC' - "</option>" + == '<option value="id1" >February 1, 2018, 10:58:59\u202fAM UTC</option>' ) assert hasattr(html, "__html__") # shows it is safe Markup @@ -37,9 +36,7 @@ def test_selected(self): html = out[0] assert ( str(html) - == '<option value="id1" selected>February 1, 2018 at 10:58:59' - " AM UTC" - "</option>" + == '<option value="id1" selected>February 1, 2018, 10:58:59\u202fAM UTC</option>' ) assert hasattr(html, "__html__") # shows it is safe Markup
Flask-Babel 2.0.0 breaks ITranslation Upgrading Flask-Babel from 1.0.0 to [2.0.0](https://github.com/python-babel/flask-babel/releases/tag/v2.0.0) makes the `ITranslation` tests fail: https://app.circleci.com/pipelines/github/ckan/ckan/1902/workflows/8ef66c69-6def-4d1b-8bbf-1678e93f56aa/jobs/9630 Basically our custom override to support multiple translation domains is never called: https://github.com/ckan/ckan/blob/d47eb0972a6f99460926e2869bd858caee1f74bf/ckan/config/middleware/flask_app.py#L97-L106 @TkTech I *think* that the way this works in Flask-babel changed as part of this change: https://github.com/python-babel/flask-babel/pull/163 but I couldn't find any docs on how the new approach works. Do you have any pointers on how to refactor this on our end?
@amercader I'll look into this, however it'll have to wait until Saturday. I'm not entirely sure how this works as-is. It seems to depend on the order it's called (?) which is prone to breaking. Under v2.0.0, the approach I think will work here is to create a: ```domain = flask_babel.Domain(translation_directories=plugin.i18n_directory(), domain=plugin.i18n_domain())``` for each plugin that defines `ITranslation`, then pass in `domain.gettext` to the templates instead of `flask_babel.gettext`. @TkTech I wasn't able to figure out your approach, so I proposed this on the Flask-Babel side: https://github.com/python-babel/flask-babel/pull/194
2023-03-09T12:09:33
ckan/ckan
7,454
ckan__ckan-7454
[ "7447" ]
4657eab9aef3fa917c59dde8efd0c820933c2e34
diff --git a/ckan/logic/action/get.py b/ckan/logic/action/get.py --- a/ckan/logic/action/get.py +++ b/ckan/logic/action/get.py @@ -759,7 +759,7 @@ def license_list(context: Context, data_dict: DataDict) -> ActionResult.LicenseL license_register = model.Package.get_license_register() licenses = license_register.values() - licenses = [l.as_dict() for l in licenses] + licenses = [l.license_dictize() for l in licenses] return licenses diff --git a/ckan/model/license.py b/ckan/model/license.py --- a/ckan/model/license.py +++ b/ckan/model/license.py @@ -46,6 +46,14 @@ def isopen(self) -> bool: self.osd_conformance == 'approved' return self._isopen + def license_dictize(self) -> dict[str, Any]: + data = self._data.copy() + if 'date_created' in data: + value = data['date_created'] + value = value.isoformat() + data['date_created'] = value + return data + class LicenseRegister(object): """Dictionary-like interface to a group of licenses."""
The API method license_list no longer works with CKAN 2.10.0 ## CKAN Version 2.10.0 ## Describe the bug Calling the API method `license_list` causes an error since version 2.10.0. ### Steps to reproduce Calling the API `/api/action/license_list`. ### Expected behavior Returns the list of the licenses. ### Additional details The error happens in this line of code: https://github.com/ckan/ckan/blob/master/ckan/logic/action/get.py#L762. The function `License.as_dict()` is being called which was removed with commit: https://github.com/ckan/ckan/commit/6937dc800366118426ce7ba9529e1523e4ef13f2 ``` ERROR [ckan.views.api] as_dict Traceback (most recent call last): File "/usr/lib/ckan/env/lib/python3.9/site-packages/ckan/model/license.py", line 37, in __getattr__ return self._data[name] File "/usr/lib/ckan/env/lib/python3.9/site-packages/ckan/model/license.py", line 186, in __getitem__ raise KeyError(key) KeyError: 'as_dict' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/ckan/env/lib/python3.9/site-packages/ckan/config/middleware/../../views/api.py", line 283, in action result = function(context, request_data) File "/usr/lib/ckan/env/lib/python3.9/site-packages/ckan/logic/__init__.py", line 551, in wrapped result = _action(context, data_dict, **kw) File "/usr/lib/ckan/env/lib/python3.9/site-packages/ckan/logic/action/get.py", line 762, in license_list licenses = [l.as_dict() for l in licenses] File "/usr/lib/ckan/env/lib/python3.9/site-packages/ckan/logic/action/get.py", line 762, in <listcomp> licenses = [l.as_dict() for l in licenses] File "/usr/lib/ckan/env/lib/python3.9/site-packages/ckan/model/license.py", line 41, in __getattr__ raise AttributeError(*e.args) AttributeError: as_dict ``` We solved the problem by re-adding the function `as_dict()`: ``` def as_dict(self): '''This method is still used in the logic of the action API 'license_list'. Please use attribute access preferably.''' return self._data.copy() ``` Shall we provide a pull request with re-adding the function or is there a better solution?
2023-03-16T13:37:12
ckan/ckan
7,463
ckan__ckan-7463
[ "7083" ]
b317fd2281bfcc5428fee73e5949c8a95f722cb2
diff --git a/ckan/common.py b/ckan/common.py --- a/ckan/common.py +++ b/ckan/common.py @@ -29,7 +29,7 @@ import simplejson as json # type: ignore # noqa: re-export import ckan.lib.maintain as maintain from ckan.config.declaration import Declaration -from ckan.types import Model +from ckan.types import Model, Request if TYPE_CHECKING: @@ -149,7 +149,7 @@ def _get_request(): return flask.request -class CKANRequest(LocalProxy): +class CKANRequest(LocalProxy[Request]): u'''Common request object This is just a wrapper around LocalProxy so we can handle some special diff --git a/ckan/config/middleware/flask_app.py b/ckan/config/middleware/flask_app.py --- a/ckan/config/middleware/flask_app.py +++ b/ckan/config/middleware/flask_app.py @@ -5,7 +5,6 @@ import sys import time import inspect -import itertools import pkgutil import logging @@ -22,7 +21,6 @@ Unauthorized, Forbidden ) -from werkzeug.routing import Rule from werkzeug.local import LocalProxy from flask_babel import Babel @@ -131,7 +129,6 @@ def make_flask_stack(conf: Union[Config, CKANConfig]) -> CKANApp: app.testing = testing app.template_folder = os.path.join(root, 'templates') app.app_ctx_globals_class = CKAN_AppCtxGlobals - app.url_rule_class = CKAN_Rule # Update Flask config with the CKAN values. We use the common config # object as values might have been modified on `load_environment` @@ -227,8 +224,11 @@ def make_flask_stack(conf: Union[Config, CKANConfig]) -> CKANApp: # WebAssets _setup_webassets(app) - # Auto-register all blueprints defined in the `views` folder + # Register Blueprints. First registered wins, so we need to register + # plugins first to be able to override core blueprints. + _register_plugins_blueprints(app) _register_core_blueprints(app) + _register_error_handler(app) # CSRF @@ -238,9 +238,6 @@ def make_flask_stack(conf: Union[Config, CKANConfig]) -> CKANApp: app.config["WTF_CSRF_FIELD_NAME"] = config.get('WTF_CSRF_FIELD_NAME') csrf.init_app(app) - # Set up each IBlueprint extension as a Flask Blueprint - _register_plugins_blueprints(app) - if config.get("ckan.csrf_protection.ignore_extensions"): log.warn(csrf_warn_extensions) _exempt_plugins_blueprints_from_csrf(csrf) @@ -428,25 +425,13 @@ def helper_functions() -> dict[str, h.HelperAttributeDict]: return dict(h=h.helper_functions) -def c_object() -> dict[str, LocalProxy]: +def c_object() -> dict[str, LocalProxy[Any]]: u''' Expose `c` as an alias of `g` in templates for backwards compatibility ''' return dict(c=g) -class CKAN_Rule(Rule): # noqa - - u'''Custom Flask url_rule_class. - - We use it to be able to flag routes defined in extensions as such - ''' - - def __init__(self, *args: Any, **kwargs: Any): - self.ckan_core = True - super(CKAN_Rule, self).__init__(*args, **kwargs) - - class CKAN_AppCtxGlobals(_AppCtxGlobals): # noqa '''Custom Flask AppCtxGlobal class (flask.g).''' @@ -470,61 +455,6 @@ class CKANFlask(MultiStaticFlask): static_folder: list[str] session_interface: SessionInterface - def can_handle_request( - self, - environ: Any) -> Union[tuple[bool, str], tuple[bool, str, str]]: - ''' - Decides whether it can handle a request with the Flask app by - matching the request environ against the route mapper - - Returns (True, 'flask_app', origin) if this is the case. - - `origin` can be either 'core' or 'extension' depending on where - the route was defined. - ''' - urls = self.url_map.bind_to_environ(environ) - - try: - rule, args = urls.match(return_rule=True) - origin = 'core' - if not getattr(rule, 'ckan_core', True): - origin = 'extension' - log.debug('Flask route match, endpoint: {0}, args: {1}, ' - 'origin: {2}'.format(rule.endpoint, args, origin)) - - # Disable built-in flask's ability to prepend site root to - # generated url, as we are going to use locale and existing - # logic is not flexible enough for this purpose - environ['SCRIPT_NAME'] = '' - - return (True, self.app_name, origin) - except HTTPException: - return (False, self.app_name) - - def register_extension_blueprint(self, blueprint: Blueprint, - **kwargs: dict[str, Any]): - ''' - This method should be used to register blueprints that come from - extensions, so there's an opportunity to add extension-specific - options. - - Sets the rule property `ckan_core` to False, to indicate that the rule - applies to an extension route. - ''' - self.register_blueprint(blueprint, **kwargs) - - # Get the new blueprint rules - bp_rules = itertools.chain.from_iterable( - v for k, v in self.url_map._rules_by_endpoint.items() - if k.startswith(u'{0}.'.format(blueprint.name)) - ) - - # This compare key will ensure the rule will be near the top. - top_compare_key = False, -100, [(-2, 0)] - for r in bp_rules: - setattr(r, "ckan_core", False) - setattr(r, "match_compare_key", lambda: top_compare_key) - def _register_plugins_blueprints(app: CKANApp): """ Resgister all blueprints defined in plugins by IBlueprint @@ -533,9 +463,9 @@ def _register_plugins_blueprints(app: CKANApp): plugin_blueprints = plugin.get_blueprint() if isinstance(plugin_blueprints, list): for blueprint in plugin_blueprints: - app.register_extension_blueprint(blueprint) + app.register_blueprint(blueprint) else: - app.register_extension_blueprint(plugin_blueprints) + app.register_blueprint(plugin_blueprints) def _exempt_plugins_blueprints_from_csrf(csrf: CSRFProtect):
diff --git a/ckan/tests/controllers/test_api.py b/ckan/tests/controllers/test_api.py --- a/ckan/tests/controllers/test_api.py +++ b/ckan/tests/controllers/test_api.py @@ -16,7 +16,7 @@ @pytest.mark.parametrize( "ver, expected, status", - [(0, 1, 404), (1, 1, 200), (2, 2, 200), (3, 3, 200), (4, 1, 404)], + [(1, 1, 200), (2, 2, 200), (3, 3, 200)], ) def test_get_api_version(ver, expected, status, app): resp = app.get(url_for("api.get_api", ver=str(ver)), status=status) diff --git a/ckan/tests/controllers/test_user.py b/ckan/tests/controllers/test_user.py --- a/ckan/tests/controllers/test_user.py +++ b/ckan/tests/controllers/test_user.py @@ -872,7 +872,7 @@ def test_csrf_token_in_g_object(self, app): password = "RandomPassword123" user = factories.User(password=password) - with app.flask_app.test_request_context() as ctx: + with app.flask_app.app_context() as ctx: app.post( url_for("user.login"), data={ @@ -887,7 +887,7 @@ def test_csrf_token_are_different_for_different_users(self, app): password = "RandomPassword123" user1 = factories.User(password=password) token_user1 = "" - with app.flask_app.test_request_context() as ctx: + with app.flask_app.app_context() as ctx: app.post( url_for("user.login"), data={ @@ -900,7 +900,7 @@ def test_csrf_token_are_different_for_different_users(self, app): user2 = factories.User(password=password) token_user2 = "" - with app.flask_app.test_request_context() as ctx: + with app.flask_app.app_context() as ctx: app.post( url_for("user.login"), data={ diff --git a/ckanext/example_flask_iblueprint/tests/test_routes.py b/ckanext/example_flask_iblueprint/tests/test_routes.py --- a/ckanext/example_flask_iblueprint/tests/test_routes.py +++ b/ckanext/example_flask_iblueprint/tests/test_routes.py @@ -19,7 +19,6 @@ def test_plugin_route(self, app): def test_plugin_route_core_flask_override(self, app): """Test extension overrides flask core route.""" res = app.get("/") - assert helpers.body_contains( res, "Hello World, this is served from an extension, " diff --git a/ckanext/example_idatasetform/tests/test_example_idatasetform.py b/ckanext/example_idatasetform/tests/test_example_idatasetform.py --- a/ckanext/example_idatasetform/tests/test_example_idatasetform.py +++ b/ckanext/example_idatasetform/tests/test_example_idatasetform.py @@ -288,7 +288,6 @@ def test_links_on_read_pages(self, current_user, app): assert page_header.find( href=url_for("fancy_type." + action, id=pkg["name"]) ) - # import ipdb; ipdb.set_trace() assert page.find(id="dataset-resources").find( href=url_for( "fancy_type_resource.read",
Update CKAN to Flask 2.2.2 (or latest) CKAN 2.9.5 and next 2.10.0 will be running under Flask 2.0.3. Migration to Flask 2.2.2 will have some work that we would address once 2.10.0 is released. Some of the key points to be able to run the latest version: - [x] We will need to update from Flask-Login `0.6.1` to `0.6.2` (See #7064 description) - [X] We will need to fix/patch/replace `flask-multistatic` since it will not work with latest Werkzeug. It looks like the package it's not being maintained in a while, since it only and last release was 6 years ago: https://pypi.org/project/flask-multistatic/#history - [x] Fixing all tests ~122 failing tests when quickly fixing `flask-multistatic` locally. - [x] We still can't update Flask-Babel to 2.0.0 as it breaks ITranslation (see https://github.com/ckan/ckan/issues/6708 and https://github.com/python-babel/flask-babel/pull/194 cc @TkTech ) -> PR https://github.com/ckan/ckan/pull/7436 - [ ] `dev-requirements.txt`: docutils pinnned at 0.17 because sphinx-rtd-theme doesn't support a bigger version - [ ] `dev-requirements.txt`: pytest-factoryboy pinnned at 2.4.0 because on 2.5.0 we get:
On the Flask-login failures, I'm pretty sure that they are caused by this change: https://github.com/maxcountryman/flask-login/pull/691 Somehow the combination of storing the logged in user in `g` instead of the stacks and the way CKAN tests with the `app` fixture are run breaks tings. We need to keep digging.
2023-03-17T16:13:15
ckan/ckan
7,464
ckan__ckan-7464
[ "7406" ]
a7029c67fe48216cffd1ad53110179a1707d302d
diff --git a/ckan/config/declaration/option.py b/ckan/config/declaration/option.py --- a/ckan/config/declaration/option.py +++ b/ckan/config/declaration/option.py @@ -366,6 +366,7 @@ def _validators_from_string(s: str) -> list[Validator]: out = [] parts = s.split() + for p in parts: if '(' in p and p[-1] == ')': name, args = p.split('(', 1)
Default to client-based sessions for new sites The Flask-Login refactor introduced changes regarding logged in users and the session. To re-cap: Flask-login stores the logged-in user identifier in the Flask session (as opposed to the `auth_tkt` in CKAN<2.10). CKAN uses [Beaker](https://beaker.readthedocs.io/en/latest/sessions.html) to manage the session, and the default session backend stores this session information as files on the server (on `/tmp`). This means that **if the session data is deleted in the server, all users will be logged out of the site**. This can happen for instance: * if the CKAN container is redeployed in a Docker / cloud setup and the session directory is not persisted * if the sessions are periodically cleaned by an external script | Action | CKAN < 2.10 | CKAN >= 2.10 | | ------ | ----------- | ------------ | | Clear cookies | User logged out | User logged out (If `remember_me` cookie is deleted) | | Clear server sessions | User still logged in | User logged out | The way to keep the old behaviour with the Beaker backend is to store the session data in the [cookie itself](https://beaker.readthedocs.io/en/latest/sessions.html#cookie-based) (but this stores *all* session data, not just the user identifier): ``` # ckan.ini beaker.session.type = cookie beaker.session.validate_key = tT0ka0aOAWEPbvSOSog7c4ZFu # These should probably be defaults anyway beaker.session.httponly = True beaker.session.secure = True beaker.session.samesite = Lax # or Strict ``` Going through the Flask-login discussion, it looks like we decided to default to storing the session in the cookie on new instances ( https://github.com/ckan/ckan/pull/6560#issuecomment-1161693905). We didn't end up implementing this in CKAN 2.10, should we aim for it in CKAN 2.11? If we go ahead this will probably just involve configuration and documentation changes.
Decisions from the dev meeting: * Aim to implement this change in 2.10.1, not 2.11. It should only involve configuration and documentation changes and only affect new sites. * CHANGELOG should clearly document the new default configuration in case existing sites want to replicate it. Things to make sure to mention: * Potential issues with the cookie size if users store large amounts of data in the session * `beaker.session.samesite` needs to be `Lax` if using some third-party Auth otherwise the cookie will get dropped (@Zharktas please expand/correct) * Users can always set up server side sessions with redis or DB if necessary
2023-03-17T16:28:51
ckan/ckan
7,483
ckan__ckan-7483
[ "7336" ]
ed5367765fb22686b3aa5446d83aa8a9e57207ba
diff --git a/ckan/config/environment.py b/ckan/config/environment.py --- a/ckan/config/environment.py +++ b/ckan/config/environment.py @@ -116,6 +116,14 @@ def update_config() -> None: webassets_init() + # these are collections of all template/public paths registered by + # extensions. Each call to `tk.add_template_directory` or + # `tk.add_public_directory` updates these collections. We have to reset + # them in order to remove templates/public files that came from plugins + # that were once enabled but are disabled right now. + config["plugin_template_paths"] = [] + config["plugin_public_paths"] = [] + for plugin in reversed(list(p.PluginImplementations(p.IConfigurer))): # must do update in place as this does not work: # config = plugin.update_config(config)
diff --git a/ckan/tests/config/data/home/about.html b/ckan/tests/config/data/home/about.html new file mode 100644 --- /dev/null +++ b/ckan/tests/config/data/home/about.html @@ -0,0 +1 @@ +YOU WILL NOT FIND ME diff --git a/ckan/tests/config/test_environment.py b/ckan/tests/config/test_environment.py --- a/ckan/tests/config/test_environment.py +++ b/ckan/tests/config/test_environment.py @@ -89,3 +89,11 @@ def test_siteurl_removes_backslash(ckan_config): def test_missing_timezone(): with pytest.raises(CkanConfigurationException): environment.update_config() + + [email protected]_config("plugin_template_paths", [ + os.path.join(os.path.dirname(__file__), "data") +]) +def test_plugin_template_paths_reset(app): + resp = app.get("/about") + assert "YOU WILL NOT FIND ME" not in resp
Pytest ckan_config does not override configurations from test.ini ## CKAN version 2.9, master ## Describe the bug By configuring some variable in test.ini like `ckan.plugins` reduces duplication in tests themselves. However if test requires some other variable like different plugins, using `ckan_config` decorator does not override the variable from test.ini ### Steps to reproduce Create tests with ckan.plugins set to something in test.ini Implement a test with decorator: @pytest.mark.ckan_config('ckan.plugins', 'some_plugin') ### Expected behavior Test should use plugin given in decorator and not in test.ini
Example of this issue can be found here: Plugins configured in test.ini https://github.com/vrk-kpa/ckanext-xroad_integration/blob/4e7ebf0f9a3f3a21196018f7b94d4d70aae649dc/test.ini#L17 failing test: https://github.com/vrk-kpa/ckanext-xroad_integration/blob/4e7ebf0f9a3f3a21196018f7b94d4d70aae649dc/ckanext/xroad_integration/tests/test_plugin.py#L134-L138 The failing test run can be seen here https://github.com/vrk-kpa/ckanext-xroad_integration/actions/runs/3938128022/jobs/6736463077 at least of awhile, the test fails as it tries to include templates from the extensions defined in test.ini Turned out that the `ckan_config` mark actually overrides the configuration. The problem lies much deeper. Every test uses [a snapshot of configuration object](https://github.com/ckan/ckan/blob/master/ckan/tests/pytest_ckan/ckan_setup.py#L79-L80) which is created [before the first test](https://github.com/ckan/ckan/blob/master/ckan/tests/pytest_ckan/ckan_setup.py#L49-L50). At this moment, CKAN loads all the plugins from the config file and saves template paths as `config['extra_template_paths']`. Then, even if you load no plugins via the `ckan_config` mark, the config snapshot already contains all the template paths. It behaves like a global variable. If, for example, you add `@pytest.mark.ckan_config("extra_template_paths", "")` decorator to the problematic test, it will pass. It's still a bug, but it has a different scale. In order to solve this issue, we have to compute template paths in realtime or re-compute `extra_template_paths` whenever `with_plugins` fixture is applied(this option sounds like a better plan)
2023-03-21T16:31:45
ckan/ckan
7,493
ckan__ckan-7493
[ "7170" ]
71d08f931db610faf8669c3a35cf184abec0d9d0
diff --git a/ckan/logic/action/get.py b/ckan/logic/action/get.py --- a/ckan/logic/action/get.py +++ b/ckan/logic/action/get.py @@ -55,6 +55,7 @@ _and_ = sqlalchemy.and_ _func = sqlalchemy.func _case = sqlalchemy.case +_null = sqlalchemy.null def site_read(context: Context, data_dict: Optional[DataDict]=None) -> bool: @@ -183,12 +184,13 @@ def member_list(context: Context, data_dict: DataDict) -> ActionResult.MemberLis # User must be able to update the group to remove a member from it _check_access('group_show', context, data_dict) - q = model.Session.query(model.Member).\ - filter(model.Member.group_id == group.id).\ + q = model.Session.query(model.Member) + if obj_type: + q = model.Member.all(obj_type) + + q = q.filter(model.Member.group_id == group.id).\ filter(model.Member.state == "active") - if obj_type: - q = q.filter(model.Member.table_name == obj_type) if capacity: q = q.filter(model.Member.capacity == capacity) diff --git a/ckan/model/group.py b/ckan/model/group.py --- a/ckan/model/group.py +++ b/ckan/model/group.py @@ -110,10 +110,32 @@ def get(cls, reference: str) -> Optional["Member"]: member = cls.by_name(reference) return member + @classmethod + def all(cls, object_type: str) -> Query[Self]: + """Filter members that do not have an associated entity. + + Given the design of the member table and the lack of a CASCADE trigger, manually + deleted entities will not properly drop it's member row. This can cause member_list + to return users or datasets that no longer exist in the system. + + Returns a query object + """ + import ckan.model as model + + models = { "user" : model.User, "package": model.Package, "group": model.Group} + outer_mdl = models.get(object_type, None) + q = meta.Session.query(cls).filter(model.Member.table_name == object_type) + if outer_mdl: + q = q.join(outer_mdl, outer_mdl.id == model.Member.table_id, isouter=True).\ + filter(outer_mdl.state=='active') + return q + + def related_packages(self) -> list[_package.Package]: # TODO do we want to return all related packages or certain ones? return meta.Session.query(_package.Package).filter_by( id=self.table_id).all() + def __str__(self): # refer to objects by name, not ID, to help debugging
diff --git a/ckan/tests/logic/action/test_get.py b/ckan/tests/logic/action/test_get.py --- a/ckan/tests/logic/action/test_get.py +++ b/ckan/tests/logic/action/test_get.py @@ -2828,6 +2828,46 @@ def test_user_delete_marks_membership_of_org_as_deleted(self): assert len(org_members) == 0 + def test_user_list_excludes_deleted_users_not_marked_membership_of_org_as_deleted(self): + sysadmin = factories.Sysadmin() + org = factories.Organization() + user = factories.User() + context = {"user": sysadmin["name"]} + + member_dict = { + "username": user["id"], + "id": org["id"], + "role": "member", + } + helpers.call_action( + "organization_member_create", context, **member_dict + ) + + org_members = helpers.call_action( + "member_list", + context, + id=org["id"], + object_type="user", + capacity="member", + ) + + assert len(org_members) == 1 + assert org_members[0][0] == user["id"] + assert org_members[0][1] == "user" + + model.Session.delete(model.User.get(user["id"])) + model.Session.commit() + + org_members = helpers.call_action( + "member_list", + context, + id=org["id"], + object_type="user", + capacity="member", + ) + + assert len(org_members) == 0 + @pytest.mark.usefixtures("non_clean_db") class TestFollow(object):
member_list action returns deleted users **CKAN version** 2.9.7 **Describe the bug** The `member_list` action with `'object_type': 'user'` returns all member users, including deleted ones This was fixed with #3078 but relies on the `user_delete` action. If I manually delete a user from the DB, this will fail. **Steps to reproduce** Trying to iterate all members, you will get `toolkit.ObjectNotFound` for deleted users ```py users = toolkit.get_action('member_list')(context, { 'id': container['id'], 'object_type': 'user', }) for user in users: duser = toolkit.get_action('user_show')(context, {'id': user[0]}) ``` **Expected behavior** `member_list` action must return only active users **Possible fix** Add an extra DB query to filter only active users
To mimic the behaviour at the Python level introduced in #3078 (mark membership records as deleted when you delete a user via `user_delete`) we need to implement a foreign key with the proper `CASCADE` behaviour between the `user` and `member` tables. Additionally we can add an extra check to the SQLAlchemy query in `member_list` that filters member records who don't have a record in the `user` table. The same fix can probably be applied for datasets @avdata99, @amercader I'm interested to work on this issue.
2023-03-24T10:06:10
ckan/ckan
7,494
ckan__ckan-7494
[ "7364" ]
71d08f931db610faf8669c3a35cf184abec0d9d0
diff --git a/ckan/logic/auth/__init__.py b/ckan/logic/auth/__init__.py --- a/ckan/logic/auth/__init__.py +++ b/ckan/logic/auth/__init__.py @@ -46,24 +46,19 @@ def _get_object(context: Context, def _get_object(context: Context, data_dict: Optional[DataDict], name: str, class_name: str) -> Any: - # return the named item if in the context, or get it from model.class_name - try: - return context[name] - except KeyError: - model = context['model'] - if not data_dict: - data_dict = {} - id = data_dict.get('id', None) - if not id: - raise logic.ValidationError({ - "message": 'Missing id, can not get {0} object'.format( - class_name)}) - obj = getattr(model, class_name).get(id) - if not obj: - raise logic.NotFound - # Save in case we need this again during the request - context[name] = obj - return obj + # return the named item from model.class_name + model = context['model'] + if not data_dict: + data_dict = {} + id = data_dict.get('id', None) + if not id: + raise logic.ValidationError({ + "message": 'Missing id, can not get {0} object'.format( + class_name)}) + obj = getattr(model, class_name).get(id) + if not obj: + raise logic.NotFound + return obj def get_package_object( diff --git a/ckan/logic/validators.py b/ckan/logic/validators.py --- a/ckan/logic/validators.py +++ b/ckan/logic/validators.py @@ -500,7 +500,7 @@ def ignore_not_package_admin(key: FlattenKey, data: FlattenDataDict, pkg = context.get('package') if pkg: try: - logic.check_access('package_change_state',context) + logic.check_access('package_change_state',context, {"id": pkg.id}) authorized = True except logic.NotAuthorized: authorized = False @@ -540,7 +540,7 @@ def ignore_not_group_admin(key: FlattenKey, data: FlattenDataDict, group = context.get('group') if group: try: - logic.check_access('group_change_state',context) + logic.check_access('group_change_state',context, {"id": group.id}) authorized = True except logic.NotAuthorized: authorized = False diff --git a/ckan/views/dataset.py b/ckan/views/dataset.py --- a/ckan/views/dataset.py +++ b/ckan/views/dataset.py @@ -805,7 +805,11 @@ def get(self, resources_json = h.json.dumps(data.get(u'resources', [])) user = current_user.name try: - check_access(u'package_update', context) + check_access( + 'package_update', + context, + {"id": pkg_dict.get('id')} + ) except NotAuthorized: return base.abort( 403,
diff --git a/ckan/tests/logic/auth/test_init.py b/ckan/tests/logic/auth/test_init.py --- a/ckan/tests/logic/auth/test_init.py +++ b/ckan/tests/logic/auth/test_init.py @@ -19,18 +19,6 @@ def _get_function(obj_type): return _get_object_functions[obj_type] -def _get_object_in_context(obj_type): - - if obj_type == "user": - context = {"user_obj": "a_fake_object"} - else: - context = {obj_type: "a_fake_object"} - - obj = _get_function(obj_type)(context) - - assert obj == "a_fake_object" - - def _get_object_id_not_found(obj_type): with pytest.raises(logic.NotFound): @@ -43,22 +31,6 @@ def _get_object_id_none(obj_type): _get_function(obj_type)({"model": core_model}, {}) -def test_get_package_object_in_context(): - _get_object_in_context("package") - - -def test_get_resource_object_in_context(): - _get_object_in_context("resource") - - -def test_get_user_object_in_context(): - _get_object_in_context("user") - - -def test_get_group_object_in_context(): - _get_object_in_context("group") - - def test_get_package_object_id_not_found(): _get_object_id_not_found("package") @@ -105,7 +77,6 @@ def test_get_package_object_with_id(self): obj = logic_auth.get_package_object(context, {"id": dataset["id"]}) assert obj.id == dataset["id"] - assert context["package"] == obj def test_get_resource_object_with_id(self): @@ -126,7 +97,6 @@ def test_get_resource_object_with_id(self): obj = logic_auth.get_resource_object(context, {"id": resource["id"]}) assert obj.id == resource["id"] - assert context["resource"] == obj def test_get_user_object_with_id(self): @@ -143,7 +113,6 @@ def test_get_user_object_with_id(self): obj = logic_auth.get_user_object(context, {"id": user["id"]}) assert obj.id == user["id"] - assert context["user_obj"] == obj def test_get_group_object_with_id(self): @@ -157,4 +126,3 @@ def test_get_group_object_with_id(self): obj = logic_auth.get_group_object(context, {"id": group["id"]}) assert obj.id == group["id"] - assert context["group"] == obj diff --git a/ckan/tests/logic/test_logic.py b/ckan/tests/logic/test_logic.py --- a/ckan/tests/logic/test_logic.py +++ b/ckan/tests/logic/test_logic.py @@ -90,3 +90,26 @@ def test_fresh_context(): assert "model" not in cleaned_context assert "session" not in cleaned_context assert "auth_user_obj" not in cleaned_context + + +def test_check_access_auth_user_for_different_objects(): + user1 = factories.User() + user2 = factories.User() + context = {"user": user1["name"]} + + organization1 = factories.Organization(user=user1) + organization2 = factories.Organization(user=user2) + + datasets1 = [ + factories.Dataset(owner_org=organization1["id"], private=True) + for _ in range(0, 1) + ] + datasets2 = [ + factories.Dataset(owner_org=organization2["id"], private=True) + for _ in range(0, 1) + ] + dataset3 = datasets1 + datasets2 + + with pytest.raises(logic.NotAuthorized): + for dataset in dataset3: + logic.check_access("package_show", context, {'id': dataset["id"]})
Refactor old _get_object logic The authorization layer provides a _get_object method that can generate side effects if context objects are used in sequential action calls. (See #7348) https://github.com/ckan/ckan/blob/e21141098f33c54e1e3fdf0a6d19922f5d54a3f7/ckan/logic/auth/__init__.py#L46-L66 This method is part of an old implementation of a "cache like" layer that could be modernized. Newer versions of sqlalchemy and databases provide their own cache logic when doing selects queries, therefore there would be no need to implement custom logic. ### Some ideas of implementation: - `_get_object` should directly call to the database using the object id. - There would be no need to store and pass the object in the context for "later reuse".
So a good implementation for this would be to remove the logic or retrieving the object from the context and directly call the database. I'm expecting this to cause some errors elsewhere since this "cache logic" has been miss used sometimes. ## To Do: - [ ] Remove the use of `context["name"]` - [ ] Check if this also fixes #7348 - [ ] Make an overall review of the code for places set `context[name]` before calling the authorization and clean up that line since it is no longer needed. @shashigharti this is a necessary and good ticket to work if you have time! As a suggestion for the last point @shashigharti I would do a quick round of manual testing with a print statement to spot where is this being used in the system: ```python ... try: x = context[name] print(x) return x except KeyError: ... ```
2023-03-24T10:08:44
ckan/ckan
7,509
ckan__ckan-7509
[ "7508" ]
971c57f236c152b20c67b53626f45e4f1b174b77
diff --git a/ckan/lib/mailer.py b/ckan/lib/mailer.py --- a/ckan/lib/mailer.py +++ b/ckan/lib/mailer.py @@ -64,8 +64,8 @@ def _mail_recipient( else: msg.add_header(k, v) msg['Subject'] = subject - msg['From'] = _("%s <%s>") % (sender_name, mail_from) - msg['To'] = u"%s <%s>" % (recipient_name, recipient_email) + msg['From'] = utils.formataddr((sender_name, mail_from)) + msg['To'] = utils.formataddr((recipient_name, recipient_email)) msg['Date'] = utils.formatdate(time()) if not config.get('ckan.hide_version'): msg['X-Mailer'] = "CKAN %s" % ckan.__version__
diff --git a/ckan/tests/lib/test_mailer.py b/ckan/tests/lib/test_mailer.py --- a/ckan/tests/lib/test_mailer.py +++ b/ckan/tests/lib/test_mailer.py @@ -6,6 +6,7 @@ from email.header import decode_header from email.mime.text import MIMEText from email.parser import Parser +import email.utils import ckan.lib.helpers as h import ckan.lib.mailer as mailer @@ -199,10 +200,10 @@ def test_from_field_format(self, mail_server): msgs = mail_server.get_smtp_messages() msg = msgs[0] - expected_from_header = "{0} <{1}>".format( + expected_from_header = email.utils.formataddr(( config.get("ckan.site_title"), config.get("smtp.mail_from") - ) + )) assert expected_from_header in msg[3]
Mailer doesn't quote names in To/From headers ## CKAN version 2.9.8, though it doesn't appear to have changed on 2.10 ## Describe the bug The username and site title are included in the To/From headers respectively, but they aren't quoted. When one contains, for example, commas, it's displayed as several addresses. (When site_title is `Dept of A, B, and C`, the emails appear to be from `Dept@{host}, of@{host}, A@{host}, B@{host}, and C,`) ### Steps to reproduce Steps to reproduce the behavior: Set a site_title to a string containing commas and trigger an email somehow. I've been using `ckanext-harvester` notifications. ### Expected behavior That the name would be quoted and therefore show as `Dept of A, B, and C`. ### Additional details #4343 appeared to address the same / a similar issue
2023-03-30T08:35:20
ckan/ckan
7,518
ckan__ckan-7518
[ "7507" ]
39853f5d467e35766b873210f40a2414258681f7
diff --git a/ckanext/activity/views.py b/ckanext/activity/views.py --- a/ckanext/activity/views.py +++ b/ckanext/activity/views.py @@ -810,6 +810,10 @@ def user_activity(id: str) -> str: @bp.route("/dashboard/", strict_slashes=False) def dashboard() -> str: + if tk.current_user.is_anonymous: + tk.h.flash_error(tk._(u'Not authorized to see this page')) + return tk.h.redirect_to(u'user.login') + context = cast( Context, {
Activity stream plugin on CKAN 2.10 does not redirect unauthenticated dashboard to login page ## CKAN version 2.10 ## Describe the bug The dashboard views are meant to redirect to the login page if the user is not authenticated. However, the activity stream plugin does not. Instead, it encounters a "User not found" error. ### Steps to reproduce - Start a CKAN 2.10 instance with the 'activity' plugin enabled. - Go to /dashboard/datasets without logging in. You should see the login page. - Go to /dashboard without logging in. You should see the login page but will actually see an error. ### Expected behavior The /dashboard URL should redirect to the login page if not logged in. ### Additional details The error message appears to originate from `ckan.views.user._extra_template_variables`; the activity plugin is attempting to preload user information.
2023-04-04T05:33:25
ckan/ckan
7,533
ckan__ckan-7533
[ "5753" ]
739bf0b28b9ace2d91d5e9a214854102dc57c186
diff --git a/ckanext/datastore/backend/postgres.py b/ckanext/datastore/backend/postgres.py --- a/ckanext/datastore/backend/postgres.py +++ b/ckanext/datastore/backend/postgres.py @@ -18,6 +18,7 @@ import datetime import hashlib import json +import decimal from collections import OrderedDict from urllib.parse import ( @@ -832,6 +833,8 @@ def convert(data: Any, type_name: str) -> Any: return data.isoformat() if isinstance(data, (int, float)): return data + if isinstance(data, (int, float, decimal.Decimal)): + return data return str(data)
diff --git a/ckanext/datastore/tests/test_search.py b/ckanext/datastore/tests/test_search.py --- a/ckanext/datastore/tests/test_search.py +++ b/ckanext/datastore/tests/test_search.py @@ -3,6 +3,7 @@ import json import pytest import sqlalchemy.orm as orm +import decimal import ckan.lib.create_test_data as ctd import ckan.logic as logic @@ -1848,6 +1849,28 @@ def test_search_limit(self): assert [res[u"the year"] for res in result["records"]] == [2014, 2013] assert result[u"records_truncated"] + @pytest.mark.ckan_config("ckan.plugins", "datastore") + @pytest.mark.usefixtures("clean_datastore", "with_plugins") + def test_search_numeric_data_through_sql(self): + resource = factories.Resource() + data = { + "resource_id": resource["id"], + "force": True, + "fields": [ + {"id": "foo", "type": "numeric"}, + {"id": "bar", "type": "numeric"} + ], + "records": [ + {"foo": 1, "bar": 2}, + {"foo": 3, "bar": 4} + ] + } + result = helpers.call_action("datastore_create", **data) + sql = 'SELECT * FROM "{0}"'.format(resource["id"]) + result = helpers.call_action("datastore_search_sql", sql=sql) + record_new = result["records"] + assert (isinstance(record_new[0]["foo"], decimal.Decimal)) + class TestDatastoreSearchRecordsFormat(object): @pytest.mark.ckan_config("ckan.plugins", "datastore")
datastore_search_sql returns numeric as string **CKAN version** 2.8.4 **Describe the bug** Datastore api function datastore_search_sql returns fields with type "numeric" as string. **Steps to reproduce** Create a resource and upload the following CSV file, making sure it was uploaded to the datastore: ```csv foo,bar 1,2 3,4 ``` Then access it via api using datastore_search_sql, for example like this: GET https://beta.ckan.org/api/3/action/datastore_search_sql?sql=SELECT * from "66ca1e80-e697-40ce-9c50-2579b59e48f2" Which returns: ```json { "help": "https://beta.ckan.org/api/3/action/help_show?name=datastore_search_sql", "success": true, "result": { "sql": "SELECT * from \"66ca1e80-e697-40ce-9c50-2579b59e48f2\"", "records": [ { "_id": 1, "_full_text": "'1':1 '2':2", "foo": "1", "bar": "2" }, { "_id": 2, "_full_text": "'3':1 '4':2", "foo": "3", "bar": "4" } ], "fields": [ { "id": "_id", "type": "int4" }, { "id": "_full_text", "type": "tsvector" }, { "id": "foo", "type": "numeric" }, { "id": "bar", "type": "numeric" } ] } } ``` In the response json, result.records.foo is a string. **Expected behavior** result.records.foo should be a number in the json response **Additional details** If the data is instead queried with GET https://beta.ckan.org/api/3/action/datastore_search?resource_id=66ca1e80-e697-40ce-9c50-2579b59e48f2 The response is: ```json { "help": "https://beta.ckan.org/api/3/action/help_show?name=datastore_search", "success": true, "result": { "include_total": true, "limit": 100, "records_format": "objects", "resource_id": "66ca1e80-e697-40ce-9c50-2579b59e48f2", "total_estimation_threshold": null, "records": [ { "_id": 1, "foo": 1, "bar": 2 }, { "_id": 2, "foo": 3, "bar": 4 } ], "fields": [ { "id": "_id", "type": "int" }, { "id": "foo", "type": "numeric" }, { "id": "bar", "type": "numeric" } ], "_links": { "start": "/api/3/action/datastore_search?resource_id=66ca1e80-e697-40ce-9c50-2579b59e48f2", "next": "/api/3/action/datastore_search?resource_id=66ca1e80-e697-40ce-9c50-2579b59e48f2&offset=100" }, "total": 2, "total_was_estimated": false } } ``` So this seems like an inconsistency to me.
2023-04-11T07:11:33
ckan/ckan
7,545
ckan__ckan-7545
[ "7037" ]
a9f7cc1217e1006d3d482ed2645b22dc418e2fdf
diff --git a/ckanext/datastore/backend/postgres.py b/ckanext/datastore/backend/postgres.py --- a/ckanext/datastore/backend/postgres.py +++ b/ckanext/datastore/backend/postgres.py @@ -1934,26 +1934,28 @@ def datastore_search( rank_columns) where = _where_clauses(data_dict, fields_types) select_cols = [] - records_format = data_dict.get(u'records_format') + records_format = data_dict.get('records_format') for field_id in field_ids: - fmt = u'to_json({0})' if records_format == u'lists' else u'{0}' + fmt = '{0}' + if records_format == 'lists': + fmt = "coalesce(to_json({0}),'null')" typ = fields_types.get(field_id, '') - if typ == u'nested': - fmt = u'({0}).json' - elif typ == u'timestamp': - fmt = u"to_char({0}, 'YYYY-MM-DD\"T\"HH24:MI:SS')" - if records_format == u'lists': - fmt = u"to_json({0})".format(fmt) - elif typ.startswith(u'_') or typ.endswith(u'[]'): - fmt = u'array_to_json({0})' + if typ == 'nested': + fmt = "coalesce(({0}).json,'null')" + elif typ == 'timestamp': + fmt = "to_char({0}, 'YYYY-MM-DD\"T\"HH24:MI:SS')" + if records_format == 'lists': + fmt = f"coalesce(to_json({fmt}), 'null')" + elif typ.startswith('_') or typ.endswith('[]'): + fmt = "coalesce(array_to_json({0}),'null')" if field_id in rank_columns: select_cols.append((fmt + ' as {1}').format( rank_columns[field_id], identifier(field_id))) continue - if records_format == u'objects': - fmt += u' as {0}' + if records_format == 'objects': + fmt += ' as {0}' select_cols.append(fmt.format(identifier(field_id))) query_dict['distinct'] = data_dict.get('distinct', False)
diff --git a/ckanext/datastore/tests/test_search.py b/ckanext/datastore/tests/test_search.py --- a/ckanext/datastore/tests/test_search.py +++ b/ckanext/datastore/tests/test_search.py @@ -2181,3 +2181,46 @@ def test_fts_on_field_calculates_ranks_when_full_text_is_given(self): ranks = [r["rank"] for r in result["records"]] assert len(result["records"]) == 2 assert len(set(ranks)) == 2 + + @pytest.mark.ckan_config("ckan.plugins", "datastore") + @pytest.mark.usefixtures("clean_datastore", "with_plugins") + def test_results_with_nulls(self): + ds = factories.Dataset() + r = helpers.call_action( + "datastore_create", + resource={"package_id": ds["id"]}, + fields=[ + {"id": "num", "type": "numeric"}, + {"id": "dt", "type": "timestamp"}, + {"id": "txt", "type": "text"}, + {"id": "lst", "type": "_text"}, + ], + records=[ + {"num": 10, "dt": "2020-01-01", "txt": "aaab", "lst": ["one", "two"]}, + {"num": 9, "dt": "2020-01-02", "txt": "aaab"}, + {"num": 9, "txt": "aaac", "lst": ["one", "two"]}, + {}, # all nulls + ], + ) + assert helpers.call_action( + "datastore_search", + resource_id=r["resource_id"], + records_format=u"lists", + sort=u"num nulls last, dt nulls last", + )["records"] == [ + [2, 9, "2020-01-02T00:00:00", "aaab", None], + [3, 9, None, "aaac", ["one", "two"]], + [1, 10, "2020-01-01T00:00:00", "aaab", ["one", "two"]], + [4, None, None, None, None], + ] + assert helpers.call_action( + "datastore_search", + resource_id=r["resource_id"], + records_format=u"objects", + sort=u"num nulls last, dt nulls last", + )["records"] == [ + {"_id": 2, "num": 9, "dt": "2020-01-02T00:00:00", "txt": "aaab", "lst": None}, + {"_id": 3, "num": 9, "dt": None, "txt": "aaac", "lst": ["one", "two"]}, + {"_id": 1, "num": 10, "dt": "2020-01-01T00:00:00", "txt": "aaab", "lst": ["one", "two"]}, + {"_id": 4, "num": None, "dt": None, "txt": None, "lst": None}, + ]
Downloading data with null value as JSON causes an Internal Server Error **CKAN version** 2.8.4 and 2.8.10 **Describe the bug** When downloading data (which is stored in the datastore) as JSON, an internal server error occurs if the data contains a null value. The error occurs when each row has at least one column with a null value. **Steps to reproduce** The bug can be reproduced via ckan API: 1. Create resource: http://myserver:myport/api/3/action/resource_create with body form data: package_id (ID of an existing dataset) and name (name of resource) 2. Create datastore and add data: http://myserver:myport/api/3/action/datastore_create with body raw data: `{ "resource_id": "54317d3a-3a26-4911-911d-57c615639756", "force": "true", "fields": [ { "id": "id", "type": "numeric" }, { "id": "name", "type": "text" } ], "primary_key": "id", "records": [ { "id": "1", "name": null } ] }` 3. Download data as JSON: http://myserver:myport/datastore/dump/54317d3a-3a26-4911-911d-57c615639756?format=json **Expected behavior** A download should be possible without error. In this particular case the resulting json file will be empty. (In case of multiple rows of data, ckan already ignors the rows with null values and downloads the rest of data successfully.) **Additional details** Stack trace: ![image](https://user-images.githubusercontent.com/111954802/186346787-383ff280-ad23-416e-a195-a8501b54da4a.png)
Hi @wardi @bpeXX , should we allow users to upload files with `null` values? I tried to reproduce the issue but received a different error that is associated with the #6713 issue, I've fixed issue #6713 and will raise the PR soon. But I found that when downloading a resource in json format, [this](https://github.com/ckan/ckan/blob/master/ckanext/datastore/backend/postgres.py#L1372-#L1378) query runs. I found that when concatenating with the `||` operator, the values from a row that contains a `null` value, the output for that particular row changes into a blank row, I've tested with multiple queries containing `null` values, I believe this is the default behavior of PostgreSQL. We can have a different approach where we can replace the `null` value with another value, but that would be an alteration of the file itself. I believe a better approach would be to raise a ValidationError message if a `null` value is found in the file. @wardi, I'd like to know your opinion on this. Hi @bpeXX - Just wondering if you tested this issue with CKAN 2.9 (2.9.5 or master)? Hi @kowh-ai, unfortunately I did not test the issue with CKAN 2.9 since our application is based on CKAN 2.8.4. @bpeXX @kowh-ai I am having the same issue on CKAN 2.9.7 left a comment in issue page: https://github.com/ckan/ckan/issues/6713#issuecomment-1507271171
2023-04-13T20:56:42
ckan/ckan
7,546
ckan__ckan-7546
[ "7507" ]
a9f7cc1217e1006d3d482ed2645b22dc418e2fdf
diff --git a/ckanext/activity/views.py b/ckanext/activity/views.py --- a/ckanext/activity/views.py +++ b/ckanext/activity/views.py @@ -810,6 +810,10 @@ def user_activity(id: str) -> str: @bp.route("/dashboard/", strict_slashes=False) def dashboard() -> str: + if tk.current_user.is_anonymous: + tk.h.flash_error(tk._(u'Not authorized to see this page')) + return tk.h.redirect_to(u'user.login') + context = cast( Context, {
Activity stream plugin on CKAN 2.10 does not redirect unauthenticated dashboard to login page ## CKAN version 2.10 ## Describe the bug The dashboard views are meant to redirect to the login page if the user is not authenticated. However, the activity stream plugin does not. Instead, it encounters a "User not found" error. ### Steps to reproduce - Start a CKAN 2.10 instance with the 'activity' plugin enabled. - Go to /dashboard/datasets without logging in. You should see the login page. - Go to /dashboard without logging in. You should see the login page but will actually see an error. ### Expected behavior The /dashboard URL should redirect to the login page if not logged in. ### Additional details The error message appears to originate from `ckan.views.user._extra_template_variables`; the activity plugin is attempting to preload user information.
2023-04-13T23:03:43
ckan/ckan
7,578
ckan__ckan-7578
[ "7573" ]
b98af141595d842275985244eb4966782ede5d55
diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py --- a/ckan/lib/helpers.py +++ b/ckan/lib/helpers.py @@ -367,12 +367,6 @@ def url_for(*args: Any, **kw: Any) -> str: # remove __ckan_no_root and add after to not pollute url no_root = kw.pop('__ckan_no_root', False) - # All API URLs generated should provide the version number - if kw.get('controller') == 'api' or args and args[0].startswith('api.'): - ver = kw.get('ver') - if not ver: - raise Exception('API URLs must specify the version (eg ver=3)') - _auto_flask_context = _get_auto_flask_context() try: if _auto_flask_context: diff --git a/ckanext/datastore/plugin.py b/ckanext/datastore/plugin.py --- a/ckanext/datastore/plugin.py +++ b/ckanext/datastore/plugin.py @@ -80,6 +80,7 @@ def update_config(self, config: CKANConfig): templates_base = config.get('ckan.base_templates_folder') p.toolkit.add_template_directory(config, templates_base) + p.toolkit.add_resource('assets', 'ckanext_datastore') self.backend = DatastoreBackend.get_active_backend() # IConfigurable
diff --git a/ckanext/datastore/tests/test_info.py b/ckanext/datastore/tests/test_info.py --- a/ckanext/datastore/tests/test_info.py +++ b/ckanext/datastore/tests/test_info.py @@ -73,15 +73,14 @@ def test_api_info(app): page = app.get(url, status=200) - # check we built all the urls ok - expected_urls = ( - "http://test.ckan.net/api/3/action/datastore_create", - "http://test.ckan.net/api/3/action/datastore_upsert", - "<code>http://test.ckan.net/api/3/action/datastore_search", - "http://test.ckan.net/api/3/action/datastore_search_sql", - "url: 'http://test.ckan.net/api/3/action/datastore_search'", - "http://test.ckan.net/api/3/action/datastore_search" + # check we built some urls, examples properly + expected_html = ( + "http://test.ckan.net/api/action/datastore_search", + "http://test.ckan.net/api/action/datastore_search_sql", + '<pre class="example-curl"><code class="language-bash"', + f'"sql": "SELECT * FROM \\"{resource["id"]}\\" WHERE', + "RemoteCKAN('http://test.ckan.net/', apikey=API_TOKEN)", ) content = page.get_data(as_text=True) - for url in expected_urls: - assert url in content + for html in expected_html: + assert html in content
CKAN Data API extensions This is a placeholder ticket for work on improving the CKAN Data API template and making it extendable for new client languages and for cases when the example data can be generated to match the specific table (e.g. w/table designer)
2023-05-08T23:33:33
ckan/ckan
7,618
ckan__ckan-7618
[ "7617" ]
3c676e3cf1f075c5e9bae3b625b86247edf3cc1d
diff --git a/ckanext/datastore/helpers.py b/ckanext/datastore/helpers.py --- a/ckanext/datastore/helpers.py +++ b/ckanext/datastore/helpers.py @@ -239,3 +239,12 @@ def datastore_search_sql_enabled(*args: Any) -> bool: return tk.asbool(config) except (tk.ObjectNotFound, tk.NotAuthorized): return False + + +def datastore_rw_resource_url_types() -> list[str]: + """ + Return a list of resource url_type values that do not require passing + force=True when used with datastore_create, datastore_upsert, + datastore_delete + """ + return ["datastore"] diff --git a/ckanext/datastore/logic/action.py b/ckanext/datastore/logic/action.py --- a/ckanext/datastore/logic/action.py +++ b/ckanext/datastore/logic/action.py @@ -700,10 +700,14 @@ def _check_read_only(context: Context, resource_id: str): ''' res = p.toolkit.get_action('resource_show')( context, {'id': resource_id}) - if res.get('url_type') != 'datastore': + if res.get('url_type') not in ( + p.toolkit.h.datastore_rw_resource_url_types() + ): raise p.toolkit.ValidationError({ - 'read-only': ['Cannot edit read-only resource. Either pass' - '"force=True" or change url_type to "datastore"'] + 'read-only': ['Cannot edit read-only resource because changes ' + 'made may be lost. Use a resource created for ' + 'editing e.g. with datastore_create or use ' + '"force=True" to ignore this warning.'] }) diff --git a/ckanext/datastore/plugin.py b/ckanext/datastore/plugin.py --- a/ckanext/datastore/plugin.py +++ b/ckanext/datastore/plugin.py @@ -258,10 +258,12 @@ def datastore_search(self, context: Context, data_dict: dict[str, Any], def get_helpers(self) -> dict[str, Callable[..., object]]: conf_dictionary = datastore_helpers.datastore_dictionary conf_sql_enabled = datastore_helpers.datastore_search_sql_enabled + rw_url_types = datastore_helpers.datastore_rw_resource_url_types return { 'datastore_dictionary': conf_dictionary, - 'datastore_search_sql_enabled': conf_sql_enabled + 'datastore_search_sql_enabled': conf_sql_enabled, + 'datastore_rw_resource_url_types': rw_url_types, } # IForkObserver
Customize R/W datastore resource `url_type`s The datastore API returns an error when `datastore_create`, `datastore_upsert`, `datastore_delete` are used on resources that have a resource_type value different than `"datastore"`, unless `force=True` is passed. This is a *good* thing for the common case of data in the datastore created by xloader/datapusher because any updated data will be lost on the next reload. Other cases (like table designer resources) should be able to allow use without `force=True`, so I'd like to make it possible for plugins to define new resource types that allow datastore modifications.
2023-05-29T19:06:58
ckan/ckan
7,625
ckan__ckan-7625
[ "7622" ]
7cbad5b156e2295a3a5d062f35fc066d06d1855e
diff --git a/ckanext/datastore/backend/postgres.py b/ckanext/datastore/backend/postgres.py --- a/ckanext/datastore/backend/postgres.py +++ b/ckanext/datastore/backend/postgres.py @@ -1018,7 +1018,7 @@ def create_table(context: Context, data_dict: dict[str, Any]): def alter_table(context: Context, data_dict: dict[str, Any]): - '''Adds new columns and updates column info (stored as comments). + '''Add/remove columns and updates column info (stored as comments). :param resource_id: The resource ID (i.e. postgres table name) :type resource_id: string @@ -1038,20 +1038,15 @@ def alter_table(context: Context, data_dict: dict[str, Any]): if not supplied_fields: supplied_fields = current_fields check_fields(context, supplied_fields) - field_ids = _pluck('id', supplied_fields) records = data_dict.get('records') new_fields: list[dict[str, Any]] = [] + field_ids: set[str] = set(f['id'] for f in supplied_fields) + current_ids: set[str] = set(f['id'] for f in current_fields) - for num, field in enumerate(supplied_fields): + for field in supplied_fields: # check to see if field definition is the same or and # extension of current fields - if num < len(current_fields): - if field['id'] != current_fields[num]['id']: - raise ValidationError({ - 'fields': [(u'Supplied field "{0}" not ' - u'present or in wrong order').format( - field['id'])] - }) + if field['id'] in current_ids: # no need to check type as field already defined. continue @@ -1102,6 +1097,11 @@ def alter_table(context: Context, data_dict: dict[str, Any]): identifier(f['id']), info_sql)) + for id_ in current_ids - field_ids - set(f['id'] for f in new_fields): + alter_sql.append('ALTER TABLE {0} DROP COLUMN {1};'.format( + identifier(data_dict['resource_id']), + identifier(id_))) + if alter_sql: context['connection'].execute( u';'.join(alter_sql).replace(u'%', u'%%')) diff --git a/ckanext/datastore/logic/action.py b/ckanext/datastore/logic/action.py --- a/ckanext/datastore/logic/action.py +++ b/ckanext/datastore/logic/action.py @@ -32,7 +32,7 @@ def datastore_create(context: Context, data_dict: dict[str, Any]): The datastore_create action allows you to post JSON data to be stored against a resource. This endpoint also supports altering tables, aliases and indexes and bulk insertion. This endpoint can be called - multiple times to initially insert more data, add fields, change the + multiple times to initially insert more data, add/remove fields, change the aliases or indexes as well as the primary keys. To create an empty datastore resource and a CKAN resource at the same time, @@ -80,7 +80,8 @@ def datastore_create(context: Context, data_dict: dict[str, Any]): Please note that setting the ``aliases``, ``indexes`` or ``primary_key`` replaces the existing aliases or constraints. Setting ``records`` appends - the provided records to the resource. + the provided records to the resource. Setting ``fields`` without including + all existing fields will remove the others and the data they contain. **Results:**
diff --git a/ckanext/datastore/tests/test_create.py b/ckanext/datastore/tests/test_create.py --- a/ckanext/datastore/tests/test_create.py +++ b/ckanext/datastore/tests/test_create.py @@ -307,6 +307,30 @@ def test_calculate_record_count(self): last_analyze = when_was_last_analyze(resource["id"]) assert last_analyze is not None + def test_remove_columns(self): + resource = factories.Resource() + data = { + "resource_id": resource["id"], + "fields": [ + {"id": "col_a", "type": "text"}, + {"id": "col_b", "type": "text"}, + {"id": "col_c", "type": "text"}, + {"id": "col_d", "type": "text"}, + ], + "force": True, + } + helpers.call_action("datastore_create", **data) + data = { + "resource_id": resource["id"], + "fields": [ + {"id": "col_a", "type": "text"}, + {"id": "col_c", "type": "text"}, + ], + "force": True, + } + helpers.call_action("datastore_create", **data) + info = helpers.call_action("datastore_info", id=resource["id"]) + assert [f['id'] for f in info['fields']] == ['col_a', 'col_c'] class TestDatastoreCreate(object): @@ -1125,43 +1149,6 @@ def test_guess_types(self, app): u"nested", # count3 ], types - ### fields resupplied in wrong order - - data = { - "resource_id": resource.id, - "fields": [ - {"id": "author", "type": "text"}, - {"id": "count"}, - {"id": "date"}, # date and book in wrong order - {"id": "book"}, - {"id": "count2"}, - {"id": "extra", "type": "text"}, - {"id": "date2"}, - ], - "records": [ - { - "book": "annakarenina", - "author": "tolstoy", - "count": 1, - "date": "2005-12-01", - "count2": 2, - "count3": 432, - "date2": "2005-12-01", - } - ], - } - - headers = {"Authorization": self.sysadmin_token} - res = app.post( - "/api/action/datastore_create", - json=data, - headers=headers, - status=409, - ) - res_dict = json.loads(res.data) - - assert res_dict["success"] is False - @pytest.mark.ckan_config("ckan.plugins", "datastore") @pytest.mark.usefixtures("with_plugins") def test_datastore_create_with_invalid_data_value(self, app):
datastore_create: allow deleting columns `datastore_create` can be used to create and update datastore tables including adding columns, but if you remove columns from the `fields` list they are not deleted. Assuming no-one is relying on this behavior, let's allow deleting datastore columns by removing them from the `fields` list passed to `datastore_create`. If someone is relying on columns not passed being kept we could add a `delete_columns` option but that's not the most consistent/obvious API. ## Current behavior: - Columns passed to `fields` must match, in order, existing columns or a ValidationError is raised. Existing columns missing at the end are ignored. - Column types must be either included in `fields` or guessable from the first value in the `records` list or a ValidationError is raised. - Keys included in the first value of the `records` list are added as new columns if they don't match an existing column id. Types for these columns are guessed from the corresponding value in the first record. ## Proposed change: - When `fields` column list is passed, ignore the order (no longer cause ValidationError) and any existing columns not included will be deleted ### Aside: current datastore_create type guessing logic | first record value | guessed type | | --- | --- | | object, list | `json` (with `nested` composite type used for historical reasons) | | int | `int4` (with overflow/underflow issues) | | float | `float8` (IEEE float, fast but not exact) | | string parseable as int | `int4` (with overflow/underflow issues) | | string parseable as float | `numeric` (exact, slow) | | string in one of 8 different date/time formats | `timestamp` with postgres DMY/MDY configuration determining parsing order (errors possible) | | otherwise | `text` |
2023-06-01T21:46:07
ckan/ckan
7,697
ckan__ckan-7697
[ "7683" ]
b630bfb7903a7d0c6a621c59231eebf7163bb4d6
diff --git a/ckanext/datastore/backend/__init__.py b/ckanext/datastore/backend/__init__.py --- a/ckanext/datastore/backend/__init__.py +++ b/ckanext/datastore/backend/__init__.py @@ -53,16 +53,6 @@ class DatastoreException(Exception): pass -class InvalidDataError(Exception): - """Exception that's raised if you try to add invalid data to the datastore. - - For example if you have a column with type "numeric" and then you try to - add a non-numeric value like "foo" to it, this exception should be raised. - - """ - pass - - class DatastoreBackend: """Base class for all datastore backends. diff --git a/ckanext/datastore/backend/postgres.py b/ckanext/datastore/backend/postgres.py --- a/ckanext/datastore/backend/postgres.py +++ b/ckanext/datastore/backend/postgres.py @@ -36,7 +36,7 @@ from psycopg2.extras import register_default_json, register_composite import distutils.version from sqlalchemy.exc import (ProgrammingError, IntegrityError, - DBAPIError, DataError) + DBAPIError, DataError, DatabaseError) import ckan.plugins as plugins from ckan.common import CKANConfig, config @@ -46,7 +46,6 @@ DatastoreException, _parse_sort_clause ) -from ckanext.datastore.backend import InvalidDataError log = logging.getLogger(__name__) @@ -1108,11 +1107,6 @@ def alter_table(context: Context, data_dict: dict[str, Any]): def insert_data(context: Context, data_dict: dict[str, Any]): - """ - - :raises InvalidDataError: if there is an invalid value in the given data - - """ data_dict['method'] = _INSERT result = upsert_data(context, data_dict) return result @@ -1156,11 +1150,7 @@ def upsert_data(context: Context, data_dict: dict[str, Any]): try: context['connection'].execute(sql_string, rows) - except sqlalchemy.exc.DataError as err: - raise InvalidDataError( - toolkit._("The data was invalid: {}" - ).format(_programming_error_summary(err))) - except sqlalchemy.exc.DatabaseError as err: + except (DatabaseError, DataError) as err: raise ValidationError( {u'records': [_programming_error_summary(err)]}) @@ -2007,8 +1997,6 @@ def create(self, context: Context, data_dict: dict[str, Any]): nor can the ordering of them be changed. They can be extended though. Any error results in total failure! For now pass back the actual error. Should be transactional. - :raises InvalidDataError: if there is an invalid value in the given - data ''' engine = get_write_engine() context['connection'] = engine.connect() diff --git a/ckanext/datastore/logic/action.py b/ckanext/datastore/logic/action.py --- a/ckanext/datastore/logic/action.py +++ b/ckanext/datastore/logic/action.py @@ -15,9 +15,7 @@ import ckan.plugins as p import ckanext.datastore.logic.schema as dsschema import ckanext.datastore.helpers as datastore_helpers -from ckanext.datastore.backend import ( - DatastoreBackend, InvalidDataError -) +from ckanext.datastore.backend import DatastoreBackend from ckanext.datastore.backend.postgres import identifier log = logging.getLogger(__name__) @@ -156,10 +154,7 @@ def datastore_create(context: Context, data_dict: dict[str, Any]): 'alias': [u'"{0}" is not a valid alias name'.format(alias)] }) - try: - result = backend.create(context, data_dict) - except InvalidDataError as err: - raise p.toolkit.ValidationError({'message': str(err)}) + result = backend.create(context, data_dict) if data_dict.get('calculate_record_count', False): backend.calculate_record_count(data_dict['resource_id']) # type: ignore
diff --git a/ckanext/datastore/tests/test_create.py b/ckanext/datastore/tests/test_create.py --- a/ckanext/datastore/tests/test_create.py +++ b/ckanext/datastore/tests/test_create.py @@ -1180,7 +1180,7 @@ def test_datastore_create_with_invalid_data_value(self, app): assert res_dict["success"] is False assert res_dict["error"]["__type"] == "Validation Error" - assert res_dict["error"]["message"].startswith("The data was invalid") + assert 'invalid input syntax for type numeric' in str(res_dict["error"]) diff --git a/ckanext/datastore/tests/test_db.py b/ckanext/datastore/tests/test_db.py --- a/ckanext/datastore/tests/test_db.py +++ b/ckanext/datastore/tests/test_db.py @@ -2,7 +2,6 @@ import unittest.mock as mock import pytest -import sqlalchemy.exc import ckan.lib.jobs as jobs import ckan.plugins as p @@ -128,44 +127,6 @@ def _assert_created_index_on( ) [email protected]("ckanext.datastore.backend.postgres._get_fields") -def test_upsert_with_insert_method_and_invalid_data(mock_get_fields_function): - """upsert_data() should raise InvalidDataError if given invalid data. - - If the type of a field is numeric and upsert_data() is given a whitespace - value like " ", it should raise DataError. - - In this case we're testing with "method": "insert" in the data_dict. - - """ - mock_connection = mock.Mock() - mock_connection.execute.side_effect = sqlalchemy.exc.DataError( - "statement", "params", "orig", connection_invalidated=False - ) - - context = {"connection": mock_connection} - data_dict = { - "fields": [{"id": "value", "type": "numeric"}], - "records": [ - {"value": 0}, - {"value": 1}, - {"value": 2}, - {"value": 3}, - {"value": " "}, # Invalid numeric value. - {"value": 5}, - {"value": 6}, - {"value": 7}, - ], - "method": "insert", - "resource_id": "fake-resource-id", - } - - mock_get_fields_function.return_value = data_dict["fields"] - - with pytest.raises(backend.InvalidDataError): - db.upsert_data(context, data_dict) - - class TestGetAllResourcesIdsInDatastore(object): @pytest.mark.ckan_config(u"ckan.plugins", u"datastore") @pytest.mark.usefixtures(u"with_plugins", u"clean_db") diff --git a/ckanext/datastore/tests/test_upsert.py b/ckanext/datastore/tests/test_upsert.py --- a/ckanext/datastore/tests/test_upsert.py +++ b/ckanext/datastore/tests/test_upsert.py @@ -780,6 +780,32 @@ def test_empty_string_instead_of_null(self): rec = search_result["records"][0] assert rec == {'_id': 1, 'pk': '1000', 'n': None, 'd': None} + @pytest.mark.ckan_config("ckan.plugins", "datastore") + @pytest.mark.usefixtures("clean_datastore", "with_plugins") + def test_insert_wrong_type(self): + resource = factories.Resource() + data = { + "resource_id": resource["id"], + "force": True, + "fields": [ + {"id": "num", "type": "int"}, + ], + } + helpers.call_action("datastore_create", **data) + + data = { + "resource_id": resource["id"], + "force": True, + "method": "insert", + "records": [ + {"num": "notanumber"} + ], + } + + with pytest.raises(ValidationError) as context: + helpers.call_action("datastore_upsert", **data) + assert u'invalid input syntax for integer: "notanumber"' in str(context.value) + class TestDatastoreUpdate(object): # Test action 'datastore_upsert' with 'method': 'update'
datastore: InvalidDataError is an invalid data error ## CKAN version all ## Describe the bug using the wrong type of data for a column with the datastore raises an internal exception InvalidDataError from the API call. This exception isn't caught by the API view because it's not an expected exception type for APIs. ### Steps to reproduce create a datastore table with e.g. and int type column and pass a string that can't be parsed as an int with the API. API responds with 500 server error. e.g. ```bash $ ckanapi action datastore_create \ resource:'{"package_id":"an-existing-package"}' \ fields:'[{"id":"num", "type":"int"}]' ... $ ckanapi action datastore_upsert method=insert \ resource_id=resource-id-from-above \ records:'[{"num":"notanum"}]' ... File "/srv/app/src_extensions/ckan/ckanext/datastore/backend/postgres.py", line 1602, in upsert upsert_data(context, data_dict) File "/srv/app/src_extensions/ckan/ckanext/datastore/backend/postgres.py", line 1160, in upsert_data raise InvalidDataError( ckanext.datastore.backend.InvalidDataError: The data was invalid: invalid input syntax for type integer: "notanum" ``` ### Expected behavior actions should raise a validation error so they can be caught by the API view and not cause a server error. ### Additional details
2023-07-07T02:29:15
ckan/ckan
7,719
ckan__ckan-7719
[ "7718" ]
6dc1696e2fe752203b6afd548317babe73096d01
diff --git a/ckan/lib/dictization/model_dictize.py b/ckan/lib/dictization/model_dictize.py --- a/ckan/lib/dictization/model_dictize.py +++ b/ckan/lib/dictization/model_dictize.py @@ -35,7 +35,6 @@ import ckan.lib.munge as munge import ckan.model as model from ckan.types import Context -from ckan.common import config ## package save @@ -64,7 +63,8 @@ def group_list_dictize( if with_package_counts and 'dataset_counts' not in group_dictize_context: # 'dataset_counts' will already be in the context in the case that # group_list_dictize recurses via group_dictize (groups in groups) - group_dictize_context['dataset_counts'] = get_group_dataset_counts() + group_dictize_context['dataset_counts'] = get_group_dataset_counts( + logic.fresh_context(context)) if context.get('with_capacity'): group_list = [ group_dictize( @@ -323,14 +323,19 @@ def _get_members(context: Context, group: model.Group, return q.all() -def get_group_dataset_counts() -> dict[str, Any]: +def get_group_dataset_counts(search_context: Context) -> dict[str, Any]: '''For all public groups, return their dataset counts, as a SOLR facet''' - query = search.PackageSearchQuery() - q: dict[str, Any] = {'q': '', - 'fl': 'groups', 'facet.field': ['groups', 'owner_org'], - 'facet.limit': -1, 'rows': 1} - query.run(q) - return query.facets + q: dict[str, Any] = { + 'facet.limit': -1, + 'facet.field': ['groups', 'owner_org'], + 'fl': 'groups', + 'rows': 0, + 'include_private': True, + } + # FIXME: layer violation, like get_packages_for_this_group below + search_results = logic.get_action('package_search')( + search_context, q) + return search_results['facets'] def group_dictize(group: model.Group, context: Context, @@ -376,14 +381,7 @@ def get_packages_for_this_group(group_: model.Group, q['fq'] = '+groups:"{0}"'.format(group_.name) if group_.is_organization: - is_group_member = (context.get('user') and - authz.has_user_permission_for_group_or_org( - group_.id, context.get('user'), 'read')) - if is_group_member: - q['include_private'] = True - else: - if config.get('ckan.auth.allow_dataset_collaborators'): - q['include_private'] = True + q['include_private'] = True if not just_the_count: # package_search limits 'rows' anyway, so this is only if you @@ -395,9 +393,7 @@ def get_packages_for_this_group(group_: model.Group, else: q['rows'] = packages_limit - search_context = cast( - Context, dict((k, v) for (k, v) in context.items() - if k != 'schema')) + search_context = logic.fresh_context(context) search_results = logic.get_action('package_search')( search_context, q) return search_results['count'], search_results['results']
diff --git a/ckan/tests/lib/dictization/test_model_dictize.py b/ckan/tests/lib/dictization/test_model_dictize.py --- a/ckan/tests/lib/dictization/test_model_dictize.py +++ b/ckan/tests/lib/dictization/test_model_dictize.py @@ -264,7 +264,7 @@ def test_group_dictize_with_package_count(self): context = { "model": model, "session": model.Session, - "dataset_counts": model_dictize.get_group_dataset_counts(), + "dataset_counts": model_dictize.get_group_dataset_counts({}), } group = model_dictize.group_dictize( @@ -308,7 +308,7 @@ def test_group_dictize_for_org_with_package_count(self): context = { "model": model, "session": model.Session, - "dataset_counts": model_dictize.get_group_dataset_counts(), + "dataset_counts": model_dictize.get_group_dataset_counts({}), } org = model_dictize.group_dictize(
wrong counts in group_list with include_dataset_count=True ## CKAN version all ## Describe the bug Permission labels aren't checked for group or organization dataset counts leading to incorrect counts ### Steps to reproduce Use an IPermissionLabels plugin or package collaborators to give permission to a dataset to a user that wouldn't normally be able to view it. When that user views the group or organization page that dataset isn't included in the package counts shown. ### Expected behavior dataset counts in group_list (and by extension group and organization pages) should match the counts on the dataset search pages ### Additional details https://github.com/ckan/ckan/blob/9956f92925740957b119bd7c6719ee202eb51082/ckan/lib/dictization/model_dictize.py#L326-L333 is performing a solr query that mimics the one in `package_search` but is incomplete. We're better off moving this up to the logic layer and calling `package_search` so we're sure to get correct results.
2023-07-26T20:17:38
ckan/ckan
7,761
ckan__ckan-7761
[ "7748" ]
6dc1696e2fe752203b6afd548317babe73096d01
diff --git a/ckanext/datastore/backend/postgres.py b/ckanext/datastore/backend/postgres.py --- a/ckanext/datastore/backend/postgres.py +++ b/ckanext/datastore/backend/postgres.py @@ -1124,6 +1124,7 @@ def upsert_data(context: Context, data_dict: dict[str, Any]): records = data_dict['records'] sql_columns = ", ".join( identifier(name) for name in field_names) + num = -1 if method == _INSERT: rows = [] @@ -1151,8 +1152,10 @@ def upsert_data(context: Context, data_dict: dict[str, Any]): try: context['connection'].execute(sql_string, rows) except (DatabaseError, DataError) as err: - raise ValidationError( - {u'records': [_programming_error_summary(err)]}) + raise ValidationError({ + 'records': [_programming_error_summary(err)], + 'records_row': num, + }) elif method in [_UPDATE, _UPSERT]: unique_keys = _get_unique_key(context, data_dict) @@ -1228,8 +1231,9 @@ def upsert_data(context: Context, data_dict: dict[str, Any]): sql_string, used_values + unique_values) except sqlalchemy.exc.DatabaseError as err: raise ValidationError({ - u'records': [_programming_error_summary(err)], - u'_records_row': num}) + 'records': [_programming_error_summary(err)], + 'records_row': num, + }) # validate that exactly one row has been updated if results.rowcount != 1: @@ -1263,8 +1267,9 @@ def upsert_data(context: Context, data_dict: dict[str, Any]): (used_values + unique_values) * 2) except sqlalchemy.exc.DatabaseError as err: raise ValidationError({ - u'records': [_programming_error_summary(err)], - u'_records_row': num}) + 'records': [_programming_error_summary(err)], + 'records_row': num, + }) def validate(context: Context, data_dict: dict[str, Any]):
diff --git a/ckanext/datastore/tests/test_create.py b/ckanext/datastore/tests/test_create.py --- a/ckanext/datastore/tests/test_create.py +++ b/ckanext/datastore/tests/test_create.py @@ -1368,7 +1368,10 @@ def test_create_trigger_exception(self, app): records=[{u"spam": u"spam"}, {u"spam": u"EGGS"}], triggers=[{u"function": u"spamexception_trigger"}], ) - assert error.value.error_dict == {u"records": [u'"EGGS"? Yeeeeccch!']} + assert error.value.error_dict == { + "records": ['"EGGS"? Yeeeeccch!'], + "records_row": 1, + } @pytest.mark.ckan_config("ckan.plugins", "datastore") @pytest.mark.usefixtures("clean_datastore", "with_plugins") @@ -1402,5 +1405,6 @@ def test_upsert_trigger_exception(self, app): records=[{u"spam": u"spam"}, {u"spam": u"BEANS"}], ) assert error.value.error_dict == { - u"records": [u'"BEANS"? Yeeeeccch!'] + "records": ['"BEANS"? Yeeeeccch!'], + "records_row": 1, }
datastore doesn't report row number for errors on upsert/create ## CKAN version all ## Describe the bug `datastore_create` and `datastore_upsert` can fail while loading data and will report an error but do not indicate which row was being processed when the error occurred. ### Steps to reproduce e.g. ```bash ckanapi action package_create name=foo ckanapi action datastore_create \ resource:'{"package_id":"foo"}' records:'[{"a":1}, {"a":"two"}]' ``` raises: ```python ckan.logic.ValidationError: None - { 'records': ['invalid input syntax for type integer: "two"'] } ``` ### Expected behavior There should be an indication of which row triggered the failure to make it easier to find bad data in large updates ### Additional details There's no established pattern for returning the position of an error within a list in other ckan api calls, other than doing something like (for an error in the 5th row): ```python ckan.logic.ValidationError: None - { 'records': [ {},{},{},{},{"a":['invalid input syntax for type integer: "two"']} ] } ``` But: - we don't get back information from postgres on the column name for type errors - if upserting hundreds of rows we might need to create lists with hundreds of empty dicts just to indicate a position - this is not backwards compatible for clients expecting a list of strings in `records` I'm proposing to do this instead (for an error in the 5th row): ```python ckan.logic.ValidationError: None - { 'records': ['invalid input syntax for type integer: "two"'], 'records_row': 4 ] } ``` i.e. add a 0-based `records_row` value when returning an error where we know which row in records triggered the database error. Love to hear your thoughts on this this change.
note this was accidentally partially implemented in #3428 as part of other changes but not discussed in the ticket, and the key used was `_records_row`. This ticket is to properly implement `records_row` for `insert` and `create` failures and to update the name (remove leading hyphen) for other cases.
2023-08-25T20:57:15
ckan/ckan
7,775
ckan__ckan-7775
[ "7664" ]
cff1cbad3d355bf393511b648314c15ca2cdf3ff
diff --git a/ckan/lib/search/index.py b/ckan/lib/search/index.py --- a/ckan/lib/search/index.py +++ b/ckan/lib/search/index.py @@ -6,9 +6,8 @@ import logging import collections import json -import datetime import re -from dateutil.parser import parse +from dateutil.parser import parse, ParserError as DateParserError from typing import Any, NoReturn, Optional import six @@ -235,27 +234,22 @@ def index_package(self, pkg_dict['dataset_type'] = pkg_dict['type'] # clean the dict fixing keys and dates - # FIXME where are we getting these dirty keys from? can we not just - # fix them in the correct place or is this something that always will - # be needed? For my data not changing the keys seems to not cause a - # problem. new_dict = {} - bogus_date = datetime.datetime(1, 1, 1) for key, value in pkg_dict.items(): key = six.ensure_str(key) if key.endswith('_date'): + if not value: + continue try: - date = parse(value, default=bogus_date) - if date != bogus_date: - value = date.isoformat() + 'Z' - else: - # The date field was empty, so dateutil filled it with - # the default bogus date - value = None - except (IndexError, TypeError, ValueError): - log.error('%r: %r value of %r is not a valid date', pkg_dict['id'], key, value) + date = parse(value) + value = date.isoformat() + if not date.tzinfo: + value += 'Z' + except DateParserError: + log.warning('%r: %r value of %r is not a valid date', pkg_dict['id'], key, value) continue new_dict[key] = value + pkg_dict = new_dict for k in ('title', 'notes', 'title_string'):
diff --git a/ckan/tests/lib/search/test_index.py b/ckan/tests/lib/search/test_index.py --- a/ckan/tests/lib/search/test_index.py +++ b/ckan/tests/lib/search/test_index.py @@ -124,6 +124,7 @@ def test_index_date_field(self): "extras": [ {"key": "test_date", "value": "2014-03-22"}, {"key": "test_tim_date", "value": "2014-03-22 05:42:14"}, + {"key": "test_full_iso_date", "value": "2019-10-10T01:15:00Z"}, ] } ) @@ -142,6 +143,31 @@ def test_index_date_field(self): response.docs[0]["test_tim_date"].strftime("%Y-%m-%d %H:%M:%S") == "2014-03-22 05:42:14" ) + assert ( + response.docs[0]["test_full_iso_date"].strftime("%Y-%m-%d %H:%M:%S") + == "2019-10-10 01:15:00" + ) + + def test_index_date_empty_value(self): + + pkg_dict = self.base_package_dict.copy() + pkg_dict.update( + { + "extras": [ + {"key": "test_empty_date", "value": ""}, + {"key": "test_none_date", "value": None}, + ] + } + ) + + self.package_index.index_package(pkg_dict) + + response = self.solr_client.search(q="name:monkey", fq=self.fq) + + assert len(response) == 1 + + assert "test_empty_date" not in response.docs[0] + assert "test_none_date" not in response.docs[0] def test_index_date_field_wrong_value(self):
CKAN is incorrectly adding Z timezone indicator to datetime being passed to solr via search/index.py CKAN version: 2.9.9 If a package datetime field is fully specified to ISO-8601 (eg collection_date=2019-10-10T01:15:00Z), on processing through the index_package method, the resulting datetime string is invalid, and unable to be parsed by solr. ### Steps to reproduce In a solr-enabled environment Have a field on a ckan schema ending in _date Using the API call create a package with a value of "2023-01-11" into the date field. - THIS WILL WORK. Using the API call, patch the package using a value for the date field of "2019-10-10T01:15:00Z" This will fail, with this error: pysolr.SolrError: Solr responded with an error (HTTP 400): [Reason: ERROR: [doc=535287a506ddae367b9fce761adb18fb] Error adding field 'collection_date'='2019-10-04T00:22:00+00:00Z' msg=Invalid Date in Date Math String:'2019-10-04T00:22:00+00:00Z'] The problem is the "double" timezone specifier: +00:00Z - it should be EITHER +00:00 OR Z, not both. ### Expected behavior If the datetime is fully specfied, that fully specfied datetime should be passed into solr, and stored correctly. ### Additional details This is the problem line of code. https://github.com/ckan/ckan/blob/fd88d1f4c52c8ee247883549ca23500693e2e2a4/ckan/lib/search/index.py#LL250C1-L250C55 The parse(value, default=bogus_date) - Line 248 statement parses the date, and the parse function adds the +00:00 tiemzone information. Adding the Z to the date.isoformat() - line 250 makes the timezone information incorrect. If Z is required when a timezone is NOT specified, then logic needs to be added to NOT add the Z if the timezone was specified and picked up by the parse. Here is the stacktrace: solr_1 | 2023-06-20 05:35:01.253 INFO (qtp1581078471-23) [ x:ckan] o.a.s.c.S.Request [ckan] webapp=/solr path=/select params={q=name:"bpa-amdb-genomics-amplicon-16s-137726-j6562_aaggagcg-gtctagtg"+OR+id:"bpa-amdb-genomics-amplicon-16s-137726-j6562_aaggagcg-gtctagtg"&fq=site_id:"default"+%2Bentity_type:package&rows=1&wt=json} hits=1 status=0 QTime=0 solr_1 | 2023-06-20 05:35:01.820 INFO (qtp1581078471-15) [ x:ckan] o.a.s.u.p.LogUpdateProcessorFactory [ckan] webapp=/solr path=/update params={commit=true}{} 0 198 ckan_1 | 2023-06-20 05:35:01,843 ERROR [ckan.lib.search] Solr returned an error: Solr responded with an error (HTTP 400): [Reason: ERROR: [doc=535287a506ddae367b9fce761adb18fb] Error adding field 'collection_date'='2019-10-04T00:22:00+00:00Z' msg=Invalid Date in Date Math String:'2019-10-04T00:22:00+00:00Z'] ckan_1 | Traceback (most recent call last): ckan_1 | File "/app/ckan/ckan/lib/search/index.py", line 304, in index_package ckan_1 | conn.add(docs=[pkg_dict], commit=commit) ckan_1 | File "/env/lib/python3.9/site-packages/pysolr.py", line 890, in add ckan_1 | return self._update(m, commit=commit, softCommit=softCommit, waitFlush=waitFlush, waitSearcher=waitSearcher, ckan_1 | File "/env/lib/python3.9/site-packages/pysolr.py", line 478, in _update ckan_1 | return self._send_request('post', path, message, {'Content-type': 'text/xml; charset=utf-8'}) ckan_1 | File "/env/lib/python3.9/site-packages/pysolr.py", line 393, in _send_request ckan_1 | raise SolrError(error_message % (resp.status_code, solr_message)) ckan_1 | pysolr.SolrError: Solr responded with an error (HTTP 400): [Reason: ERROR: [doc=535287a506ddae367b9fce761adb18fb] Error adding field 'collection_date'='2019-10-04T00:22:00+00:00Z' msg=Invalid Date in Date Math String:'2019-10-04T00:22:00+00:00Z']
2023-09-06T10:40:57
ckan/ckan
7,781
ckan__ckan-7781
[ "7409" ]
9b3eea9819f25813f06d95ae0123171a39f471c3
diff --git a/ckan/config/middleware/flask_app.py b/ckan/config/middleware/flask_app.py --- a/ckan/config/middleware/flask_app.py +++ b/ckan/config/middleware/flask_app.py @@ -139,13 +139,6 @@ def make_flask_stack(conf: Union[Config, CKANConfig]) -> CKANApp: # Do all the Flask-specific stuff before adding other middlewares - # Secret key needed for flask-debug-toolbar and sessions - if not app.config.get('SECRET_KEY'): - app.config['SECRET_KEY'] = config.get('beaker.session.secret') - if not app.config.get('SECRET_KEY'): - raise RuntimeError(u'You must provide a value for the secret key' - ' with the SECRET_KEY config option') - root_path = config.get('ckan.root_path') if debug: from flask_debugtoolbar import DebugToolbarExtension diff --git a/ckan/lib/api_token.py b/ckan/lib/api_token.py --- a/ckan/lib/api_token.py +++ b/ckan/lib/api_token.py @@ -19,7 +19,7 @@ _config_encode_secret = u"api_token.jwt.encode.secret" _config_decode_secret = u"api_token.jwt.decode.secret" -_config_secret_fallback = u"beaker.session.secret" +_config_secret_fallback = u"SECRET_KEY" _config_algorithm = u"api_token.jwt.algorithm"
diff --git a/ckan/tests/config/test_environment.py b/ckan/tests/config/test_environment.py --- a/ckan/tests/config/test_environment.py +++ b/ckan/tests/config/test_environment.py @@ -109,3 +109,22 @@ def test_config_from_envs_are_normalized(ckan_config): environment.update_config() assert ckan_config["smtp.starttls"] is False + + [email protected]_config("SECRET_KEY", "super_secret") [email protected]_config("beaker.session.secret", None) [email protected]_config("beaker.session.validate_key", None) [email protected]_config("WTF_CSRF_SECRET_KEY", None) +def test_all_secrets_default_to_SECRET_KEY(ckan_config): + + environment.update_config() + + for key in [ + "SECRET_KEY", + "beaker.session.secret", + "beaker.session.validate_key", + "WTF_CSRF_SECRET_KEY", + ]: + assert ckan_config[key] == "super_secret" + + # Note: api_token.jwt.*.secret are tested in ckan/tests/lib/test_api_token.py diff --git a/ckan/tests/config/test_middleware.py b/ckan/tests/config/test_middleware.py --- a/ckan/tests/config/test_middleware.py +++ b/ckan/tests/config/test_middleware.py @@ -78,10 +78,10 @@ def test_secret_key_is_used_if_present(app): assert app.flask_app.config[u"SECRET_KEY"] == u"super_secret_stuff" [email protected]_config(u"SECRET_KEY", None) -def test_beaker_secret_is_used_by_default(app): [email protected]_config(u"SECRET_KEY", "some_secret") +def test_SECRET_KEY_is_used_by_default(app): assert ( - app.flask_app.config[u"SECRET_KEY"] == config[u"beaker.session.secret"] + app.flask_app.config[u"SECRET_KEY"] == "some_secret" ) diff --git a/ckan/tests/lib/test_api_token.py b/ckan/tests/lib/test_api_token.py new file mode 100644 --- /dev/null +++ b/ckan/tests/lib/test_api_token.py @@ -0,0 +1,11 @@ +import pytest + +from ckan.lib.api_token import _get_secret + + [email protected]_config("SECRET_KEY", "super_secret") [email protected]_config("api_token.jwt.encode.secret", None) [email protected]_config("api_token.jwt.decode.secret", None) +def test_secrets_default_to_SECRET_KEY(): + assert _get_secret(True) == "super_secret" # Encode + assert _get_secret(False) == "super_secret" # Decode
Secrets consolidation These are to my knowledge the secrets related config options needed to run CKAN 2.10 (please mention any I missed below): | config name | `ckan generate config` default value | fallback value | | --- | --- | --- | | `beaker.session.secret` | Random token | None | | Flask's `SECRET_KEY` | Not added | `beaker.session.secret` | | `WTF_FORMS_CSRF_SECRET` | Random token | `SECRET_KEY` | | `api_token.jwt.encode.secret` | `string:%(beaker.session.secret)s` | `beaker.session.secret` | | `api_token.jwt.decode.secret` | `string:%(beaker.session.secret)s` | `beaker.session.secret` | So for historic reasons, `beaker.session.secret` ends up being the default fallback for all of these: ```mermaid graph TD; api_token.jwt.encode.secret-->beaker.session.secret; api_token.jwt.decode.secret-->beaker.session.secret; SECRET_KEY-->beaker.session.secret; WTF_FORMS_CSRF_SECRET-->SECRET_KEY; ``` More things to note: * `beaker.session.secret` is the one added to the ini file and the one all options fall back to, but if you don't set it on the ini file, the error you get is: ``` File "/home/adria/dev/pyenvs/ckan-py3/src/ckan/ckan/config/middleware/flask_app.py", line 176, in make_flask_stack raise RuntimeError(u'You must provide a value for the secret key' RuntimeError: You must provide a value for the secret key with the SECRET_KEY config option ``` * You can use `SECRET_KEY` in your ini file instead, but if you don't define `beaker.session.secret`, API calls will fail: ``` File "/home/adria/dev/pyenvs/ckan-py3/src/ckan/ckan/lib/api_token.py", line 84, in decode _get_secret(encode=False), File "/home/adria/dev/pyenvs/ckan-py3/src/ckan/ckan/lib/api_token.py", line 39, in _get_secret secret = u"string:" + config.get(_config_secret_fallback) ``` Looks like there is space to consolidate how these settings are managed and improve these inconsistencies. My feeling is that we should try to fall back to either `SECRET_KEY` or a new `ckan.secret_key` and consolidate how all keys are set in the ini file and how their defaults are handled. And think of ways of clearly documenting them.
Decisions from the dev meeting: * Use `SECRET_KEY` as the main setting: set it on the ini file with `ckan generate config` * Make all other settings use the `SECRET_KEY` value by default in the ini file (`string:%(SECRET_KEY)s`) * Make all other settings fall back to `SECRET_KEY` in the code in case they are not defined
2023-09-07T11:41:00
ckan/ckan
7,808
ckan__ckan-7808
[ "7717" ]
83220e5f5689553a380ebb40dd016a1b57f6e35e
diff --git a/ckan/lib/jobs.py b/ckan/lib/jobs.py --- a/ckan/lib/jobs.py +++ b/ckan/lib/jobs.py @@ -287,7 +287,7 @@ def execute_job(self, job: Job, *args: Any, **kwargs: Any) -> None: meta.engine.dispose() # The original implementation performs the actual fork - queue = remove_queue_name_prefix(cast(str, job.origin)) + queue = remove_queue_name_prefix(job.origin) if not job.meta: job.meta = {}
diff --git a/ckan/tests/test_coding_standards.py b/ckan/tests/test_coding_standards.py --- a/ckan/tests/test_coding_standards.py +++ b/ckan/tests/test_coding_standards.py @@ -233,7 +233,7 @@ def test_building_the_docs(): """ try: output = subprocess.check_output( - [b"python", b"setup.py", b"build_sphinx"], stderr=subprocess.STDOUT + [b"sphinx-build", b"doc", b"build/sphinx"], stderr=subprocess.STDOUT ) except subprocess.CalledProcessError as err: assert (
[Snyk] Security upgrade certifi from 2021.10.8 to 2023.7.22 <p>This PR was automatically created by Snyk using the credentials of a real user.</p><br /><h3>Snyk has created this PR to fix one or more vulnerable packages in the `pip` dependencies of this project.</h3> #### Changes included in this PR - Changes to the following files to upgrade the vulnerable dependencies to a fixed version: - requirements.txt #### Vulnerabilities that will be fixed ##### By pinning: Severity | Priority Score (*) | Issue | Upgrade | Breaking Change | Exploit Maturity :-------------------------:|-------------------------|:-------------------------|:-------------------------|:-------------------------|:------------------------- ![low severity](https://res.cloudinary.com/snyk/image/upload/w_20,h_20/v1561977819/icon/l.png "low severity") | **471/1000** <br/> **Why?** Recently disclosed, Has a fix available, CVSS 3.7 | Improper Following of a Certificate&#x27;s Chain of Trust <br/>[SNYK-PYTHON-CERTIFI-5805047](https://snyk.io/vuln/SNYK-PYTHON-CERTIFI-5805047) | `certifi:` <br> `2021.10.8 -> 2023.7.22` <br> | No | No Known Exploit (*) Note that the real score may have changed since the PR was raised. Some vulnerabilities couldn't be fully fixed and so Snyk will still find them when the project is tested again. This may be because the vulnerability existed within more than one direct dependency, but not all of the affected dependencies could be upgraded. Check the changes in this PR to ensure they won't cause issues with your project. ------------ **Note:** *You are seeing this because you or someone else with access to this repository has authorized Snyk to open fix PRs.* For more information: <img src="https://api.segment.io/v1/pixel/track?data=eyJ3cml0ZUtleSI6InJyWmxZcEdHY2RyTHZsb0lYd0dUcVg4WkFRTnNCOUEwIiwiYW5vbnltb3VzSWQiOiI0ZDYxMTQxYy02YTc4LTRjMTctYmU3ZS02OTQ4YjlmODQzMTAiLCJldmVudCI6IlBSIHZpZXdlZCIsInByb3BlcnRpZXMiOnsicHJJZCI6IjRkNjExNDFjLTZhNzgtNGMxNy1iZTdlLTY5NDhiOWY4NDMxMCJ9fQ==" width="0" height="0"/> 🧐 [View latest project report](https://app.snyk.io/org/wardi/project/7696de9f-5904-4fe5-8767-91ee8e4d2b04?utm_source&#x3D;github&amp;utm_medium&#x3D;referral&amp;page&#x3D;fix-pr) 🛠 [Adjust project settings](https://app.snyk.io/org/wardi/project/7696de9f-5904-4fe5-8767-91ee8e4d2b04?utm_source&#x3D;github&amp;utm_medium&#x3D;referral&amp;page&#x3D;fix-pr/settings) 📚 [Read more about Snyk's upgrade and patch logic](https://support.snyk.io/hc/en-us/articles/360003891078-Snyk-patches-to-fix-vulnerabilities) [//]: # (snyk:metadata:{"prId":"4d61141c-6a78-4c17-be7e-6948b9f84310","prPublicId":"4d61141c-6a78-4c17-be7e-6948b9f84310","dependencies":[{"name":"certifi","from":"2021.10.8","to":"2023.7.22"}],"packageManager":"pip","projectPublicId":"7696de9f-5904-4fe5-8767-91ee8e4d2b04","projectUrl":"https://app.snyk.io/org/wardi/project/7696de9f-5904-4fe5-8767-91ee8e4d2b04?utm_source=github&utm_medium=referral&page=fix-pr","type":"auto","patch":[],"vulns":["SNYK-PYTHON-CERTIFI-5805047"],"upgrade":[],"isBreakingChange":false,"env":"prod","prType":"fix","templateVariants":["updated-fix-title","priorityScore"],"priorityScoreList":[471],"remediationStrategy":"vuln"}) --- **Learn how to fix vulnerabilities with free interactive lessons:** 🦉 [Learn about vulnerability in an interactive lesson of Snyk Learn.](https://learn.snyk.io/?loc&#x3D;fix-pr)
2023-09-21T12:02:57
ckan/ckan
7,833
ckan__ckan-7833
[ "7832" ]
487baa372f23f92e379dc28f7fb425b940ee28a1
diff --git a/ckanext/datastore/logic/action.py b/ckanext/datastore/logic/action.py --- a/ckanext/datastore/logic/action.py +++ b/ckanext/datastore/logic/action.py @@ -4,9 +4,13 @@ from ckan.types import Context import logging from typing import Any +import json import sqlalchemy import sqlalchemy.exc +from sqlalchemy.dialects.postgresql import TEXT, JSONB +from sqlalchemy.sql.expression import func +from sqlalchemy.sql.functions import coalesce import ckan.lib.search as search import ckan.lib.navl.dictization_functions @@ -656,22 +660,28 @@ def set_datastore_active_flag( Called after creation or deletion of DataStore table. ''' - # We're modifying the resource extra directly here to avoid a - # race condition, see issue #3245 for details and plan for a - # better fix model = context['model'] - update_dict = {'datastore_active': flag} - - q = model.Session.query(model.Resource). \ - filter(model.Resource.id == data_dict['resource_id']) - resource = q.one() - - # update extras in database for record - extras = resource.extras - extras.update(update_dict) - q.update({'extras': extras}, synchronize_session=False) - + resource = model.Resource.get(data_dict['resource_id']) + assert resource + + # update extras json with a single statement + model.Session.query(model.Resource).filter( + model.Resource.id == data_dict['resource_id'] + ).update( + { + 'extras': func.jsonb_set( + coalesce( + model.resource_table.c.extras, + '{}', + ).cast(JSONB), + '{datastore_active}', + json.dumps(flag), + ).cast(TEXT) + }, + synchronize_session='fetch', + ) model.Session.commit() + model.Session.expire(resource, ['extras']) # copied from ckan.lib.search.rebuild # using validated packages can cause solr errors. @@ -690,7 +700,7 @@ def set_datastore_active_flag( }) for resource in _data_dict['resources']: if resource['id'] == data_dict['resource_id']: - resource.update(update_dict) + resource['datastore_active'] = flag psi.index_package(_data_dict) break
diff --git a/ckanext/datastore/tests/test_delete.py b/ckanext/datastore/tests/test_delete.py --- a/ckanext/datastore/tests/test_delete.py +++ b/ckanext/datastore/tests/test_delete.py @@ -50,6 +50,10 @@ def test_delete_basic(self): data = {"resource_id": resource["id"], "force": True} helpers.call_action("datastore_delete", **data) + # regression test for #7832 + resobj = model.Resource.get(data["resource_id"]) + assert resobj.extras.get('datastore_active') is False + results = execute_sql( u"select 1 from pg_views where viewname = %s", u"b\xfck2" )
set datastore active slow (unsafe?) resource update ## CKAN version all ## Describe the bug When creating or deleting a datastore table the `datastore_active` flag is updated by reading resource extras, parsing and updating the json in python, then writing to the database. This is slower than necessary and may be unsafe with other updates happening at the same time causing loss of resource metadata changes. A second related issue with this code: Resource extras are not expired from the cache when updated, so if a datastore table is created then removed, or removed then created in one session the datastore_active flag will be set incorrectly. ### Steps to reproduce Use datastore_create or datastore_delete on a resource ### Expected behavior field should be updated in database without round trip to python for parsing and updating ### Additional details Updating json in db is supported since postgresql 10.x https://www.postgresql.org/docs/10/functions-json.html
2023-09-25T20:06:31
ckan/ckan
7,841
ckan__ckan-7841
[ "7408" ]
76b929a45422d5504349a945fd6361ecacdca7a1
diff --git a/ckan/lib/base.py b/ckan/lib/base.py --- a/ckan/lib/base.py +++ b/ckan/lib/base.py @@ -24,9 +24,6 @@ log = logging.getLogger(__name__) -APIKEY_HEADER_NAME_KEY = 'apikey_header_name' -APIKEY_HEADER_NAME_DEFAULT = 'X-CKAN-API-Key' - def abort(status_code: int, detail: str = '', diff --git a/ckan/views/__init__.py b/ckan/views/__init__.py --- a/ckan/views/__init__.py +++ b/ckan/views/__init__.py @@ -38,7 +38,7 @@ def set_cors_headers_for_response(response: Response) -> Response: response.headers['Access-Control-Allow-Methods'] = \ 'POST, PUT, GET, DELETE, OPTIONS' response.headers['Access-Control-Allow-Headers'] = \ - 'X-CKAN-API-KEY, Authorization, Content-Type' + f'{config.get("apitoken_header_name")}, Content-Type' return response @@ -118,23 +118,13 @@ def identify_user() -> Optional[Response]: def _get_user_for_apitoken() -> Optional[model.User]: # type: ignore - apitoken_header_name = config.get("apikey_header_name") - + apitoken_header_name = config.get("apitoken_header_name") apitoken: str = request.headers.get(apitoken_header_name, u'') - if not apitoken: - apitoken = request.environ.get(apitoken_header_name, u'') - if not apitoken: - # For misunderstanding old documentation (now fixed). - apitoken = request.environ.get(u'HTTP_AUTHORIZATION', u'') - if not apitoken: - apitoken = request.environ.get(u'Authorization', u'') - # Forget HTTP Auth credentials (they have spaces). - if u' ' in apitoken: - apitoken = u'' + if not apitoken: return None apitoken = str(apitoken) - log.debug(u'Received API Token: %s' % apitoken) + log.debug(f'Received API Token: {apitoken[:10]}[...]') user = api_token.get_user_from_token(apitoken)
diff --git a/ckan/tests/controllers/test_package.py b/ckan/tests/controllers/test_package.py --- a/ckan/tests/controllers/test_package.py +++ b/ckan/tests/controllers/test_package.py @@ -88,11 +88,11 @@ def test_new_indexerror(self, app, user): def test_change_locale(self, app, user): url = url_for("dataset.new") - env = {"Authorization": user["token"]} - res = app.get(url, extra_environ=env) + headers = {"Authorization": user["token"]} + res = app.get(url, headers=headers) # See https://github.com/python-babel/flask-babel/issues/214 refresh_babel() - res = app.get("/de/dataset/new", extra_environ=env) + res = app.get("/de/dataset/new", headers=headers) assert helpers.body_contains(res, "Datensatz") @pytest.mark.ckan_config("ckan.auth.create_unowned_dataset", "false") diff --git a/ckan/tests/lib/test_base.py b/ckan/tests/lib/test_base.py --- a/ckan/tests/lib/test_base.py +++ b/ckan/tests/lib/test_base.py @@ -129,7 +129,7 @@ def test_cors_config_origin_allow_all_true_with_origin(app): ) assert ( response_headers["Access-Control-Allow-Headers"] - == "X-CKAN-API-KEY, Authorization, Content-Type" + == "Authorization, Content-Type" ) @@ -176,7 +176,7 @@ def test_cors_config_origin_allow_all_false_with_whitelisted_origin(app): ) assert ( response_headers["Access-Control-Allow-Headers"] - == "X-CKAN-API-KEY, Authorization, Content-Type" + == "Authorization, Content-Type" ) @@ -210,7 +210,7 @@ def test_cors_config_origin_allow_all_false_with_multiple_whitelisted_origins( ) assert ( response_headers["Access-Control-Allow-Headers"] - == "X-CKAN-API-KEY, Authorization, Content-Type" + == "Authorization, Content-Type" ) @@ -314,7 +314,7 @@ def test_cors_config_origin_allow_all_true_with_origin_2(app): ) assert ( response_headers["Access-Control-Allow-Headers"] - == "X-CKAN-API-KEY, Authorization, Content-Type" + == "Authorization, Content-Type" ) @@ -367,7 +367,7 @@ def test_cors_config_origin_allow_all_false_with_whitelisted_origin_2(app): ) assert ( response_headers["Access-Control-Allow-Headers"] - == "X-CKAN-API-KEY, Authorization, Content-Type" + == "Authorization, Content-Type" ) @@ -403,7 +403,27 @@ def test_cors_config_origin_allow_all_false_with_multiple_whitelisted_origins_2( ) assert ( response_headers["Access-Control-Allow-Headers"] - == "X-CKAN-API-KEY, Authorization, Content-Type" + == "Authorization, Content-Type" + ) + + [email protected]_config("ckan.cors.origin_allow_all", "true") [email protected]_config("ckan.site_url", "http://test.ckan.org") [email protected]_config("apitoken_header_name", "X-CKAN-API-TOKEN") [email protected]_config("ckan.plugins", "test_blueprint_plugin") [email protected]("with_plugins") +def test_cors_config_custom_auth_header(app): + """ + When using a custom value for the auth header, this should be returned + in the Access-Control-Allow-Headers header in the response. + """ + request_headers = {"Origin": "http://thirdpartyrequests.org"} + response = app.get("/simple_url", headers=request_headers) + response_headers = dict(response.headers) + + assert ( + response_headers["Access-Control-Allow-Headers"] + == "X-CKAN-API-TOKEN, Content-Type" )
Authentication header name As of CKAN 2.10, you can provide auth information in an API call: > To provide your API token in an HTTP request, include it in either an `Authorization` or `X-CKAN-API-Key` header. (The name of the HTTP header can be configured with the `apikey_header_name` option in your CKAN configuration file.) [Source](https://docs.ckan.org/en/2.10/api/index.html#authentication-and-api-tokens) This was a bit of a surprise to me, as I've always assumed that we only checked for the `Authorization` header, which you could change to `X-CKAN-API-Key` or whatever using the `apikey_header_name` conf. Except for one exception, the docs always show `Authorization` being used. So my first question is, do we want to keep this default behaviour (ie support both headers)? Regardless, I think that the [code](https://github.com/ckan/ckan/blob/e8b57b94aa083e0de922714091632e14ce29ccc0/ckan/views/__init__.py#L122-L135) that reads the headers needs a bit of cleanup (`##` Comments are mine): ```python def _get_user_for_apitoken() -> Optional[model.User]: # type: ignore ## This defaults to `X-CKAN-API-Key`, not `Authorization` (see [1]) apitoken_header_name = config.get("apikey_header_name") ## First we check if there's a `X-CKAN-API-Key` header in the request, 99.9% of the time it ain't there apitoken: str = request.headers.get(apitoken_header_name, u'') if not apitoken: ## We will never get here, headers are not added directly to the WSGI environ apitoken = request.environ.get(apitoken_header_name, u'') if not apitoken: ## Cryptic ancient comment below, but actually that's the condition that is met 99.9% of the time ## when a request with the `Authorization` header is sent (see [2]) # For misunderstanding old documentation (now fixed). apitoken = request.environ.get(u'HTTP_AUTHORIZATION', u'') if not apitoken: ## We will never get here, headers are not added directly to the WSGI environ apitoken = request.environ.get(u'Authorization', u'') # Forget HTTP Auth credentials (they have spaces). if u' ' in apitoken: apitoken = u'' ``` [1] [config declaration](https://github.com/ckan/ckan/blob/e8b57b94aa083e0de922714091632e14ce29ccc0/ckan/config/config_declaration.yaml#L371) for `apikey_header_name` [2] HTTP Request Headers are added to the [WSGI environ](https://wsgi.readthedocs.io/en/latest/definitions.html#standard-environ-keys) as `HTTP_<header_name_in_all_caps>` The `request.environ.get(u'HTTP_AUTHORIZATION', u'')` seems too brittle to rely on considering it is the one that will catch most of the requests. I would suggest refactor ad cleanup the function above to specifically check the request headers for `Authorization` and fall back to `X-CKAN-API-Key` / custom key if not found. In addition on a newly created ini file, you get the default value of `X-CKAN-API-Key`, which I think is confusing considering that we are using `Authorization` everywhere else: ```ini ## Site Settings ############################################################### ckan.site_url = http://localhost:5000 apikey_header_name = X-CKAN-API-Key ckan.cache_expires = 0 ckan.cache_enabled = false #... ``` So we could - Change the default header name to `Authorization` - Support `X-CKAN-API-Key` as special case to support current behaviour (or not, and just drop it on 2.11) - Rename `apikey_header_name` to `apitoken_header_name` using the legacy option to support the old key
Decisions from the dev meeting: * Keep support for both `Authorization` and `X-CKAN-API-Key` * Default value for `apikey_header_name` should be `Authorization` * Refactor `_get_user_for_apitoken()` clean it up and reflect the above * Rename `apikey_header_name` to `apitoken_header_name` using the legacy option to support the old key
2023-09-28T08:57:59
ckan/ckan
7,866
ckan__ckan-7866
[ "7838" ]
dcf22c80d2035e189f85f369d1c692c476853997
diff --git a/ckan/logic/action/get.py b/ckan/logic/action/get.py --- a/ckan/logic/action/get.py +++ b/ckan/logic/action/get.py @@ -1444,13 +1444,13 @@ def user_show(context: Context, data_dict: DataDict) -> ActionResult.UserShow: else: user_obj = None - if not user_obj: - raise NotFound - - context['user_obj'] = user_obj + if user_obj: + context['user_obj'] = user_obj _check_access('user_show', context, data_dict) + if not user_obj: + raise NotFound # include private and draft datasets? requester = context.get('user')
`user_show` returns `NotFound` before checking authentication for anonymous users ## CKAN version 2.10.1 ## Describe the bug The `ckan.logic.action.get.user_show` action returns a [NotFound error](https://github.com/ckan/ckan/blob/ckan-2.10.1/ckan/logic/action/get.py#L1466) before checking any auth function. This also breaks [`ckan.auth.public_user_details`](https://docs.ckan.org/en/2.10/maintaining/configuration.html#ckan-auth-public-user-details). ### Steps to reproduce Call `user_show` anonymously. Instead of "access denied", "not found" is returned. ### Expected behavior For anonymous users, an "access denied" error should be returned. Also, the configuration variable [`ckan.auth.public_user_details`](https://docs.ckan.org/en/2.10/maintaining/configuration.html#ckan-auth-public-user-details) seems to have no effect at all anymore.
2023-10-17T22:33:59
ckan/ckan
7,871
ckan__ckan-7871
[ "7869" ]
f8865626012770a2e67d4caf93cae7dbd1e4f094
diff --git a/ckan/logic/auth/__init__.py b/ckan/logic/auth/__init__.py --- a/ckan/logic/auth/__init__.py +++ b/ckan/logic/auth/__init__.py @@ -8,8 +8,8 @@ from typing_extensions import Literal import ckan.logic as logic +import ckan.authz as authz from ckan.types import Context, AuthResult, DataDict -from ckan.common import current_user if TYPE_CHECKING: import ckan.model as model_ @@ -86,7 +86,7 @@ def get_user_object( def restrict_anon(context: Context) -> AuthResult: - if current_user.is_anonymous: + if authz.auth_is_anon_user(context): return {'success': False} else: return {'success': True}
diff --git a/ckan/tests/logic/auth/test_get.py b/ckan/tests/logic/auth/test_get.py --- a/ckan/tests/logic/auth/test_get.py +++ b/ckan/tests/logic/auth/test_get.py @@ -38,7 +38,7 @@ def test_user_list_email_parameter(): class TestGetAuth(object): @pytest.mark.ckan_config(u"ckan.auth.public_user_details", False) @mock.patch("flask_login.utils._get_user") - def test_auth_user_show(self, current_user): + def test_restrict_anon_auth_when_user_is_anonymouus(self, current_user): fred = factories.User() fred["capacity"] = "editor" current_user.return_value = mock.Mock(is_anonymous=True) @@ -46,6 +46,15 @@ def test_auth_user_show(self, current_user): with pytest.raises(logic.NotAuthorized): helpers.call_auth("user_show", context=context, id=fred["id"]) + @pytest.mark.ckan_config(u"ckan.auth.public_user_details", False) + @mock.patch("flask_login.utils._get_user") + def test_restrict_anon_auth_when_user_is_in_context(self, current_user): + fred = factories.User() + fred["capacity"] = "editor" + current_user.return_value = mock.Mock(is_anonymous=True) + context = {"user": fred['id'], "model": model} + assert helpers.call_auth("user_show", context=context, id=fred["id"]) + def test_authed_user_show(self): fred = factories.User() fred["capacity"] = "editor"
current_user.is_anonymous doesn't care if context has an user ## CKAN version 2.10 ## Describe the bug While looking into why https://github.com/ckan/ckan/pull/7266 started failing on unmodified ckan, I noticed that deciphering anonymous users has changed. On 2.9 `restrict_anon` works as follows https://github.com/ckan/ckan/blob/c4e2818818e08e60bb69d64229f8dbba531f8439/ckan/logic/auth/__init__.py#L51-L55 where `authz.auth_is_anon_user` checks if the context has an user in it. On 2.10 the functionality has changed: https://github.com/ckan/ckan/blob/d46613e346f9dc551aedb54c8c24baad919f78c1/ckan/logic/auth/__init__.py#L93-L97 which does not check for context at all and the password reset started failing on 2.10. Should the `is_anonymous` check for user in context or are we just relying on what flask login says about the user?
2023-10-20T07:16:23
ckan/ckan
7,881
ckan__ckan-7881
[ "7490" ]
2c8a888b407f3c419493c4789df079f7e15b8e03
diff --git a/ckan/cli/shell.py b/ckan/cli/shell.py --- a/ckan/cli/shell.py +++ b/ckan/cli/shell.py @@ -28,7 +28,7 @@ def ipython(namespace: Mapping[str, Any], banner: str) -> None: from traitlets.config.loader import Config c = Config() - c.TerminalInteractiveShell.banner2 = banner # type: ignore + c.TerminalInteractiveShell.banner2 = banner IPython.start_ipython([], user_ns=namespace, config=c)
diff --git a/ckan/tests/config/test_sessions.py b/ckan/tests/config/test_sessions.py --- a/ckan/tests/config/test_sessions.py +++ b/ckan/tests/config/test_sessions.py @@ -82,3 +82,21 @@ def get_blueprint(self): blueprint.add_url_rule(*rule) return blueprint + + [email protected]("timeout,normalized", [ + (None, None), + ("", None), + ("123", 123), + ("1_000_000", 1_000_000), + ("-1", -1), +]) +def test_beaker_session_timeout( + monkeypatch, ckan_config, make_app, timeout, normalized +): + """Beaker timeout accepts `None`(never expires) and int(expires in + n-seconds) values. + + """ + monkeypatch.setitem(ckan_config, "beaker.session.timeout", timeout) + make_app()
Invalid session timeout value on CKAN 2.10 (logged out users unexpectedly) ## CKAN version 2.10 ## Describe the bug According to our config declaration for [`beaker.session.timeout`](https://github.com/ckan/ckan/blob/656a39de2e7ed0ce47e15080f0f5d42b66b4929b/ckan/config/config_declaration.yaml#L306): > Defaults to never expiring. But the defined default value is 600 :upside_down_face: Apart from the inconsistency, this is problematic because now that the logged-in user id is stored in the session by Flask-login, this means that users are logged out every 10 minutes. The fix is to default it to never expire as described on the docs (which is also the [Beaker default](https://beaker.readthedocs.io/en/latest/configuration.html#session-options)), but the problem is that I can set it to `None` because then Beaker complains that the value is not an int: ``` File "/home/adria/dev/pyenvs/gates/lib/python3.8/site-packages/beaker/util.py", line 290, in verify_rules params[key] = verify_options(params[key], types, message) File "/home/adria/dev/pyenvs/gates/lib/python3.8/site-packages/beaker/util.py", line 281, in verify_options raise Exception(error) Exception: Session timeout must be an integer. ``` This is because our config parsing does not support "int or None", and leaves the string "None" as the value. I guess the alternative is to put a really big number but would be good to handle it better.
Without `beaker.session.timeout = None` being possible, the `beaker.session.save_accessed_time` variable is also not configurable. ```python File "/usr/lib/ckan/.local/lib/python3.10/site-packages/beaker/middleware.py", line 126, in __init__ coerce_session_params(self.options) File "/usr/lib/ckan/.local/lib/python3.10/site-packages/beaker/util.py", line 325, in coerce_session_params raise Exception("save_accessed_time must be true to use timeout") ``` @smotornyuk this looks related to config declaration so you might have a good shot at this
2023-10-30T15:34:30
ckan/ckan
7,891
ckan__ckan-7891
[ "7812" ]
8726efb2cdc884e2a5e9b7dd5def0700dbd317f9
diff --git a/ckan/logic/validators.py b/ckan/logic/validators.py --- a/ckan/logic/validators.py +++ b/ckan/logic/validators.py @@ -772,25 +772,37 @@ def tag_not_in_vocabulary(key: FlattenKey, tag_dict: FlattenDataDict, return -def url_validator(key: FlattenKey, data: FlattenDataDict, - errors: FlattenErrorDict, context: Context) -> Any: - ''' Checks that the provided value (if it is present) is a valid URL ''' - +def url_validator( + key: FlattenKey, + data: FlattenDataDict, + errors: FlattenErrorDict, + context: Context, +) -> Any: + """Checks that the provided value (if it is present) is a valid URL""" url = data.get(key, None) if not url: return try: pieces = urlparse(url) - if all([pieces.scheme, pieces.netloc]) and \ - set(pieces.netloc) <= set(string.ascii_letters + string.digits + '-.') and \ - pieces.scheme in ['http', 'https']: - return + if all([pieces.scheme, pieces.netloc]) and pieces.scheme in [ + "http", + "https", + ]: + hostname, port = ( + pieces.netloc.split(":") + if ":" in pieces.netloc + else (pieces.netloc, None) + ) + if set(hostname) <= set( + string.ascii_letters + string.digits + "-." + ) and (port is None or port.isdigit()): + return except ValueError: # url is invalid pass - errors[key].append(_('Please provide a valid URL')) + errors[key].append(_("Please provide a valid URL")) def user_name_exists(user_name: str, context: Context) -> Any:
diff --git a/ckan/tests/logic/test_validators.py b/ckan/tests/logic/test_validators.py --- a/ckan/tests/logic/test_validators.py +++ b/ckan/tests/logic/test_validators.py @@ -899,3 +899,41 @@ def convert(tag_string): assert convert("") == [] assert convert("trailing comma,") == ["trailing comma"] assert convert("trailing comma space, ") == ["trailing comma space"] + + +def test_url_validator(): + key = ("url",) + errors = {(key): []} + + # Test with a valid URL without a port + url = {("url",): "https://example.com"} + validators.url_validator(key, url, errors, {}) + assert errors == {('url',): []} + + # Test with a valid URL with a port + url = {("url",): "https://example.com:8080"} + validators.url_validator(key, url, errors, {}) + assert errors == {('url',): []} + + # Test with an invalid URL (invalid characters in hostname) + url = {("url",): "https://exa$mple.com"} + validators.url_validator(key, url, errors, {}) + assert errors[key] == ['Please provide a valid URL'] + errors[key].clear() + + # Test with an invalid URL (invalid port) + url = {("url",): "https://example.com:80a80"} + validators.url_validator(key, url, errors, {}) + assert errors[key] == ['Please provide a valid URL'] + errors[key].clear() + + # Test with an invalid URL (no scheme) + url = {("url",): "example.com"} + validators.url_validator(key, url, errors, {}) + assert errors[key] == ['Please provide a valid URL'] + errors[key].clear() + + # Test with an invalid URL (unsupported scheme) + url = {("url",): "ftp://example.com"} + validators.url_validator(key, url, errors, {}) + assert errors[key] == ['Please provide a valid URL']
URL validator does not support ":" for specifying ports ## CKAN version 2.10.1 ## Describe the bug The URL validator https://github.com/ckan/ckan/blob/2.10/ckan/logic/validators.py#L775 does not support specifying a port. E.g. ``https://example.com/some-data`` is valid, but ``https://example.com:8080/some-data`` is **not** valid. ### Expected behavior IMO, Port numbers should be allowed in a URL. ### Additional details The `pieces.netloc`-part of the check could be adapted such that it splits it into `server_name` and `port` and checks those separately. I would be willing to write a PR if this is an acceptable approach.
2023-11-02T19:34:42
ckan/ckan
7,905
ckan__ckan-7905
[ "7736" ]
7d7b90423e2ee76a266006a87d306dff28abf4b2
diff --git a/ckan/lib/search/query.py b/ckan/lib/search/query.py --- a/ckan/lib/search/query.py +++ b/ckan/lib/search/query.py @@ -365,7 +365,7 @@ def run(self, fq.append('+site_id:%s' % solr_literal(config.get('ckan.site_id'))) # filter for package status - if not '+state:' in query.get('fq', ''): + if not any('+state:' in _item for _item in fq): fq.append('+state:active') # only return things we should be able to see
Package Search breaks when '+state' is in fq_list ## CKAN version 2.9.x, at least ## Describe the bug This call: `get_action('package_search')(None, {'fq_list':['+state:((anything other than active))']})` results in a solr query like: `...&fq=state:((anything other than active))&fq=%2Bsite_id:"default"&fq=%2Bstate:active&...` due to https://github.com/ckan/ckan/blob/2.9/ckan/lib/search/query.py#L332C11-L332C11 ``` if 'fq' in query: fq.append(query['fq']) fq.extend(query.get('fq_list', [])) # show only results from this CKAN instance fq.append('+site_id:%s' % solr_literal(config.get('ckan.site_id'))) # filter for package status if not '+state:' in query.get('fq', ''): fq.append('+state:active') ``` because the filter for package status is only checking the passed in `fq`, and not the `fq_list`. ### Expected behavior I'd expect that `fq_list` is a more convenient version of `fq`. I think a fix for this would be: ``` # filter for package status if not any('+state:' in _item for _item in fq): fq.append('+state:active') ```
2023-11-09T16:45:51
ckan/ckan
7,906
ckan__ckan-7906
[ "7768" ]
7d7b90423e2ee76a266006a87d306dff28abf4b2
diff --git a/ckanext/tracking/middleware.py b/ckanext/tracking/middleware.py --- a/ckanext/tracking/middleware.py +++ b/ckanext/tracking/middleware.py @@ -27,7 +27,9 @@ def track_request(response: Response) -> Response: request.environ.get('HTTP_ACCEPT_LANGUAGE', ''), request.environ.get('HTTP_ACCEPT_ENCODING', ''), ]) - key = hashlib.md5(key.encode()).hexdigest() + # raises a type error on python<3.9 + h = hashlib.new('md5', usedforsecurity=False) # type: ignore + key = h.update(key.encode()).hexdigest() # store key/data here sql = '''INSERT INTO tracking_raw (user_key, url, tracking_type)
Replacing MD5 hashing algorithm with SHA512 In file: common_middleware.py, method: __call__, the used hashing algorithm is no longer considered secure because it is possible to have collisions. This can lead to brute force attempt to find two or more inputs that produce the same hash. iCR suggested that safer alternative hash algorithms, such as SHA-256, SHA-512, SHA-3 are used. In the file, MD5 is used to generate a key based on several parameters and inserted into the database as `user_key`. In that case, it's recommended to use a more secure, less collision prone hash function such as- SHA256 or SHA512. ### Sponsorship and Support: This work is done by the security researchers from OpenRefactory and is supported by the [Open Source Security Foundation (OpenSSF)](https://openssf.org/): [Project Alpha-Omega](https://alpha-omega.dev/). Alpha-Omega is a project partnering with open source software project maintainers to systematically find new, as-yet-undiscovered vulnerabilities in open source code - and get them fixed – to improve global software supply chain security. The bug is found by running the Intelligent Code Repair (iCR) tool by OpenRefactory and then manually triaging the results.
Sorry for leaving it without context. Let me explain myself. Initially, I replaced the `md5` method used in file [common_middleware.py](https://github.com/ckan/ckan/blob/master/ckan/config/middleware/common_middleware.py#L59) with `sha512` for reducing the probability of hash collision, since Md5 is long deprecated. However, after the first CI run, tests were failing because the database has a field limit of 100 characters for the `user_key` field. As a result, I changed `md5` to `sha3_256` which can be contained within 100 characters limit. However, this time the tests related to the changes passed but some failed (something related to HTTP 500, where 409 was expected). Please suggest what can be done from my end. Thanks I don't think that the ckanext/datastore/tests/test_create.py::TestDatastoreCreate::test_create_alias_twice test is related -- there was a recent patch for an ordering dependent issue on that flakey test. In terms of the issue, I have a few notes: 1) Hash collisions here aren't dangerous, and could arguably be privacy enhancing. A collision would lead to undercounting distinct views. The code is creating an opaque, somewhat stable identifier that's not PII that can be used to dedup counts of views of datasets. We could replace this with something like truncated md5 with no change in any security stance. 2) Changing this hash function will invalidate any existing mappings of user tuple->count, but only to the extent that a browser update cycle will. This tends to overcount views. 3) There's a performance difference to sha3, though it's unclear if there's enough of a difference to be material. 4) Perhaps for python 3.9+, we could pass in `usedforsecurity=False` in the hash constructor to indicate that usage. Thank you for giving such a detailed explanation. The use of `md5` to generate `user_key` to track view counts of a dataset- makes sense. Also, that answers my question. I think your point #4 can be implemented to indicate the usage. I think in that case, the project would need to change it's requirement (Python 3.9+). In that case, are you planning to add a PR for it? I wouldn't bump to 3.9 for this, as it's essentially a no-op in the functional space, it's only an indication that we've considered the issue and we explicitly aren't considering this to be a security context. In this case, either we select based on python version, or leave explicit code comments to that effect to make the change when the version gets bumped. We're likely to bump the minimum requirement to 3.9 around EOY2024, as that's when 3.8 goes out of security support upstream. Well, since this isn't a security threat as you mentioned earlier, I think the `usedforsecurity=False` option can be added after you bump the min requirement for **Python to 3.9 around end of 2024.**
2023-11-10T10:27:42
ckan/ckan
7,920
ckan__ckan-7920
[ "7919" ]
56ebea07a2af44b6221d5269321cb4a773f56c68
diff --git a/ckanext/datastore/backend/postgres.py b/ckanext/datastore/backend/postgres.py --- a/ckanext/datastore/backend/postgres.py +++ b/ckanext/datastore/backend/postgres.py @@ -1096,10 +1096,11 @@ def alter_table(context: Context, data_dict: dict[str, Any]): identifier(f['id']), info_sql)) - for id_ in current_ids - field_ids - set(f['id'] for f in new_fields): - alter_sql.append('ALTER TABLE {0} DROP COLUMN {1};'.format( - identifier(data_dict['resource_id']), - identifier(id_))) + if data_dict['delete_fields']: + for id_ in current_ids - field_ids - set(f['id'] for f in new_fields): + alter_sql.append('ALTER TABLE {0} DROP COLUMN {1};'.format( + identifier(data_dict['resource_id']), + identifier(id_))) if alter_sql: context['connection'].execute( diff --git a/ckanext/datastore/logic/action.py b/ckanext/datastore/logic/action.py --- a/ckanext/datastore/logic/action.py +++ b/ckanext/datastore/logic/action.py @@ -60,6 +60,8 @@ def datastore_create(context: Context, data_dict: dict[str, Any]): :type aliases: list or comma separated string :param fields: fields/columns and their extra metadata. (optional) :type fields: list of dictionaries + :param delete_fields: set to True to remove existing fields not passed + :type delete_fields: bool (optional, default: False) :param records: the data, eg: [{"dob": "2005", "some_stuff": ["a", "b"]}] (optional) :type records: list of dictionaries diff --git a/ckanext/datastore/logic/schema.py b/ckanext/datastore/logic/schema.py --- a/ckanext/datastore/logic/schema.py +++ b/ckanext/datastore/logic/schema.py @@ -120,6 +120,7 @@ def datastore_create_schema() -> Schema: 'type': [ignore_missing], 'info': [ignore_missing], }, + 'delete_fields': [default(False), boolean_validator], 'primary_key': [ignore_missing, list_of_strings_or_string], 'indexes': [ignore_missing, list_of_strings_or_string], 'triggers': {
diff --git a/ckanext/datastore/tests/test_create.py b/ckanext/datastore/tests/test_create.py --- a/ckanext/datastore/tests/test_create.py +++ b/ckanext/datastore/tests/test_create.py @@ -307,7 +307,7 @@ def test_calculate_record_count(self): last_analyze = when_was_last_analyze(resource["id"]) assert last_analyze is not None - def test_remove_columns(self): + def test_delete_fields(self): resource = factories.Resource() data = { "resource_id": resource["id"], @@ -330,6 +330,20 @@ def test_remove_columns(self): } helpers.call_action("datastore_create", **data) info = helpers.call_action("datastore_info", id=resource["id"]) + assert [f['id'] for f in info['fields']] == [ + 'col_a', 'col_b', 'col_c', 'col_d' + ] + data = { + "resource_id": resource["id"], + "fields": [ + {"id": "col_a", "type": "text"}, + {"id": "col_c", "type": "text"}, + ], + "force": True, + "delete_fields": True, + } + helpers.call_action("datastore_create", **data) + info = helpers.call_action("datastore_info", id=resource["id"]) assert [f['id'] for f in info['fields']] == ['col_a', 'col_c']
Option for removing columns (safer default) ## CKAN version master ## Describe the bug #7625 changes the behaviour of `datastore_create` to remove fields(columns) not passed, this is useful but would be safer and more backwards compatible if we require an extra flag to indicate that's what the user intends ### Steps to reproduce Current stable versions of `datastore_create` allow you to omit existing fields when adding/updating other fields ### Expected behavior Delete fields only when a user actually asks to ### Additional details
2023-11-17T18:36:38
ckan/ckan
7,927
ckan__ckan-7927
[ "7914" ]
6648f044030711509a5aec81178cf302822b18c2
diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py --- a/ckan/lib/helpers.py +++ b/ckan/lib/helpers.py @@ -2270,7 +2270,6 @@ def resource_view_is_filterable(resource_view: dict[str, Any]) -> bool: @core_helper def resource_view_get_fields(resource: dict[str, Any]) -> list["str"]: '''Returns sorted list of text and time fields of a datastore resource.''' - if not resource.get('datastore_active'): return []
Core resource_read template relies on Datastore ## CKAN version 2.10 ## Describe the bug The datastore plugin provides its own version of the `package/resource_read.html` template if enabled. However, the core template still includes datastore-related logic, checking `datastore_active` and including datastore-specific content if true. As a result, if datastore entries exist but then the datastore is disabled, the resource view page will crash. ### Steps to reproduce - Create a CKAN instance with datastore enabled. - Create a resource. - Create a datastore entry for the resource. - Disable the datastore plugin. - Visit the resource. ### Expected behavior If the datastore plugin is not enabled, then datastore features should simply be ignored. ### Additional details If possible, please provide the full stack trace of the error raised, or add screenshots to help explain your problem. File "/mnt/local_data/ckan_venv/src/ckan/ckan/templates/package/resource_read.html", line 56, in block 'download_resource_button' <a class="dropdown-item" href="{{ h.url_for('datastore.dump', resource_id=res.id, bom=True) }}" File "/mnt/local_data/ckan_venv/src/ckan/ckan/lib/helpers.py", line 385, in url_for my_url = _url_for_flask(*args, **kw) File "/mnt/local_data/ckan_venv/src/ckan/ckan/lib/helpers.py", line 443, in _url_for_flask my_url = _flask_default_url_for(*args, **kw) File "/usr/lib/ckan/default/lib64/python3.7/site-packages/flask/helpers.py", line 338, in url_for return appctx.app.handle_url_build_error(error, endpoint, values) File "/usr/lib/ckan/default/lib64/python3.7/site-packages/flask/helpers.py", line 326, in url_for endpoint, values, method=method, force_external=external File "/usr/lib/ckan/default/lib64/python3.7/site-packages/werkzeug/routing.py", line 2315, in build raise BuildError(endpoint, values, method, self) werkzeug.routing.BuildError: Could not build url for endpoint 'datastore.dump' with values ['bom', 'resource_id']. Did you mean 'dataset.read' instead?
2023-11-21T20:32:31
ckan/ckan
7,932
ckan__ckan-7932
[ "7836" ]
8ddc2e800793d683c856b4a56f3d3f0ad3f1d168
diff --git a/ckan/logic/action/create.py b/ckan/logic/action/create.py --- a/ckan/logic/action/create.py +++ b/ckan/logic/action/create.py @@ -965,7 +965,9 @@ def user_create(context: Context, } } :type plugin_extras: dict - + :param with_apitoken: whether to create an API token for the user. + (Optional) + :type with_apitoken: bool :returns: the newly created user :rtype: dictionary @@ -974,6 +976,7 @@ def user_create(context: Context, model = context['model'] schema = context.get('schema') or ckan.logic.schema.default_user_schema() session = context['session'] + with_apitoken = data_dict.pop("with_apitoken", False) _check_access('user_create', context, data_dict) @@ -1032,10 +1035,21 @@ def user_create(context: Context, # Create dashboard for user. dashboard = model.Dashboard(user.id) + session.add(dashboard) if not context.get('defer_commit'): model.repo.commit() + if with_apitoken: + if not context['user']: + context["user"] = user.name + + # Create apitoken for user. + api_token = _get_action("api_token_create")( + context, {"user": user.name, "name": "default"} + ) + user_dict["token"] = api_token["token"] + log.debug('Created user {name}'.format(name=user.name)) return user_dict
diff --git a/ckan/tests/logic/action/test_create.py b/ckan/tests/logic/action/test_create.py --- a/ckan/tests/logic/action/test_create.py +++ b/ckan/tests/logic/action/test_create.py @@ -1270,6 +1270,41 @@ def test_user_create_defer_commit(self): with pytest.raises(logic.NotFound): helpers.call_action("user_show", id=user_dict["name"]) + def test_create_user_with_apitoken(self): + stub = factories.User.stub() + context = {"ignore_auth": True} + user_dict = { + "name": stub.name, + "email": stub.email, + "password": "test1234", + "with_apitoken": True + } + user = helpers.call_action("user_create", context={}, **user_dict) + assert user["token"] + + user_dict = {"user_id": user["name"]} + token = helpers.call_action( + "api_token_list", context=context, **user_dict + ) + assert len(token) == 1 + + def test_create_user_with_apitoken_missing_flag(self): + stub = factories.User.stub() + context = {"ignore_auth": True} + user_dict = { + "name": stub.name, + "email": stub.email, + "password": "test1234", + } + user = helpers.call_action("user_create", context={}, **user_dict) + assert "token" not in user + + user_dict = {"user_id": user["name"]} + token = helpers.call_action( + "api_token_list", context=context, **user_dict + ) + assert not token + @pytest.mark.usefixtures("clean_db") @pytest.mark.ckan_config("ckan.auth.create_user_via_web", True)
Cannot create API token via API (hen and egg) ## CKAN version 2.10.1 ## Describe the bug CKAN 2.9 supported API keys which made it possible to create a user via the API (`ckan.auth.create_user_via_api = true`) and automatically return the user's API key (`ckan.auth.create_default_api_keys = true`). Since CKAN 2.10 does not support API keys, it is not possible anymore to use the API anonymously to create users and start working as them. An API token is required to create an API token for a user. So users would have to log in via the web interface first to create an API token.
Let's add an optional parameter to `user_create` or a new endpoint that creates a user and an API token at the same time > So users would have to log in via the web interface first to create an API token. Just to be sure, if you use a sysadmin's token you can call [`api_token_create`](https://docs.ckan.org/en/2.10/api/index.html#ckan.logic.action.create.api_token_create) on the newly created user to get a token for that user back. I don't know, but adding the option to create API tokens anonymously to users that already can be created anonymously (if `ckan.auth.create_user_via_api = true`) seems to make things too easy for spammers, even if this is turned off by default. > Let's add an optional parameter to user_create or a new endpoint that creates a user and an API token at the same time For authenticated users (sysadmins) I think the best option is a new `create_api_token` param. Note that API tokens creation requires at least a name, and may require additional parameters depending on plugins installed (eg `expire_api_token`) so we need to include a parameter for those as well > > So users would have to log in via the web interface first to create an API token. > > Just to be sure, if you use a sysadmin's token you can call [`api_token_create`](https://docs.ckan.org/en/2.10/api/index.html#ckan.logic.action.create.api_token_create) on the newly created user to get a token for that user back. > > I don't know, but adding the option to create API tokens anonymously to users that already can be created anonymously (if `ckan.auth.create_user_via_api = true`) seems to make things too easy for spammers, even if this is turned off by default. My use case is this: I have a testing CKAN instance where users can connect to with a software that I have written to familiarize themselves with it. I wanted to make signup of test accounts as simple as possible (click of a button in the application). I cannot use an admin account (shipping an admin API token with the application is not an option). The user has to create the token after an account is created with the API. I could also automate it with `curl` scripts, but using the API would be the preferred option.
2023-11-22T13:37:15
ckan/ckan
7,933
ckan__ckan-7933
[ "7787" ]
8ddc2e800793d683c856b4a56f3d3f0ad3f1d168
diff --git a/ckan/logic/action/patch.py b/ckan/logic/action/patch.py --- a/ckan/logic/action/patch.py +++ b/ckan/logic/action/patch.py @@ -6,6 +6,7 @@ get_action as _get_action, check_access as _check_access, get_or_bust as _get_or_bust, + fresh_context as _fresh_context ) from ckan.types import Context, DataDict from ckan.types.logic import ActionResult @@ -68,13 +69,8 @@ def resource_patch(context: Context, ''' _check_access('resource_patch', context, data_dict) - show_context: Context = { - 'model': context['model'], - 'session': context['session'], - 'user': context['user'], - 'auth_user_obj': context['auth_user_obj'], - 'for_update': True - } + show_context: Context = _fresh_context(context) + show_context.update({'for_update': True}) resource_dict = _get_action('resource_show')( show_context, @@ -99,12 +95,7 @@ def group_patch(context: Context, ''' _check_access('group_patch', context, data_dict) - show_context: Context = { - 'model': context['model'], - 'session': context['session'], - 'user': context['user'], - 'auth_user_obj': context['auth_user_obj'], - } + show_context: Context = _fresh_context(context) group_dict = _get_action('group_show')( show_context, @@ -134,12 +125,7 @@ def organization_patch( ''' _check_access('organization_patch', context, data_dict) - show_context: Context = { - 'model': context['model'], - 'session': context['session'], - 'user': context['user'], - 'auth_user_obj': context['auth_user_obj'], - } + show_context: Context = _fresh_context(context) organization_dict = _get_action('organization_show')( show_context, @@ -168,12 +154,7 @@ def user_patch(context: Context, ''' _check_access('user_patch', context, data_dict) - show_context: Context = { - 'model': context['model'], - 'session': context['session'], - 'user': context['user'], - 'auth_user_obj': context['auth_user_obj'], - } + show_context: Context = _fresh_context(context) user_dict = _get_action('user_show')( show_context,
Some patch actions raise `ckan.logic.NotAuthorized` even though `context['ignore_auth'] = True` ## CKAN version 2.9+ ## Describe the bug The patch action functions in [ckan/logic/action/patch.py](https://github.com/ckan/ckan/tree/master/ckan/logic/action/patch.py) create a separate `show_context: Context` object that is used with a show action to retrieve the resource that is being patched. For almost all of these patch functions, the `'ignore_auth'` value from the patch action's input `context: Context` argument is not propagated to the `show_context` object. As a result, patching some resource types with `'ignore_auth': True` in the patch action's `Context` unexpectedly fails with a `ckan.logic.NotAuthorized` error. Only [`package_patch()`](https://github.com/ckan/ckan/blob/master/ckan/logic/action/patch.py#L14) correctly propagates this value. The other four patch action functions are affected: * [`resource_patch()`](https://github.com/ckan/ckan/blob/master/ckan/logic/action/patch.py#L57) * [`group_patch()`](https://github.com/ckan/ckan/blob/master/ckan/logic/action/patch.py#L88) * [`organization_patch()`](https://github.com/ckan/ckan/blob/master/ckan/logic/action/patch.py#L122) * [`user_patch()`](https://github.com/ckan/ckan/blob/master/ckan/logic/action/patch.py#L157) ## Example The following code snippet uses the Plugin Toolkit to access the [`user_patch()` function](https://github.com/ckan/ckan/blob/master/ckan/logic/action/patch.py#L157). This will fail if `user` is not authorized to perform `'user_show'`, because `'ignore_auth'` [is not propagated to `show_context`](https://github.com/ckan/ckan/blob/master/ckan/logic/action/patch.py#L171) in `user_patch()`. ```python toolkit.get_action('user_patch')( context={ 'user': user, 'ignore_auth': True, }, ) ``` A problem like this showed up while I was modifying some code in the `ckanext-ldap` plugin. I believe the reason is that at the time this is being called, a currently not-logged-in user is being passed, and such a user cannot perform `'user_show'`. Regardless, I would have expected that with `'ignore_auth'` being passed into the patch function, the action would succeed, or at least would not return an authorization error. ## Suggested fix ### Easy The easiest thing to do is just add `'ignore_auth': context.get('ignore_auth', False)` to each of the `show_context` definitions that are missing them. ### Robust A more robust fix would be to introduce a helper function, `_create_show_context()` (defined below), that each function can call to create the `show_context` object. That way, future changes to the `show_context` will be propagated to all of the patch functions. It is worth noting that I have absolutely no clue what the `'for_update'` key does. I couldn't find any documentation about it. It seems to be used in the database interaction code, but I'm not really familiar with working with databases. In any case: this key is not set consistently in the `show_context` objects across the various patch functions, so in the code below, it is an optional parameter that can be passed into the new function. ```python def _create_show_context(context: Context, for_update: bool = False) -> Context: '''Create a Context that can be used with a user_show action call. This method is internal. It is meant to be used by the patch action functions to generate a Context that can be used with a show action corresponding to the type of the patch action. The show action is used to retrieve the item that will be patched. The ``show_context`` is derived from the original patch Context, which is the ``context`` input argument. Certain values are propagated from the input ``context`` to the returned ``show_context``. :param context: Context from the original patch request :type context: Context :param for_update: if ``True``, then ``show_context['for_update'] = True``. If ``False`` (the default), then ``'for_update'`` will not be explicitly set in ``show_context``. :type for_update: bool :returns: A Context, ``show_context``, with the appropriate settings. ''' show_context: Context = { 'model': context['model'], 'session': context['session'], 'user': context['user'], 'auth_user_obj': context['auth_user_obj'], 'ignore_auth': context.get('ignore_auth', False), } if for_update: show_context['for_update'] = True return show_context ```
Good investigation, it should be a small fix. Better to use the existing `fresh_context` function than add another: https://github.com/ckan/ckan/blob/d61908bf4f2cf33e5fb306150b3c5b2893268f01/ckan/logic/__init__.py#L861-L874 `for_update` in the context makes `package_show` use `SELECT FOR UPDATE` on the database so that parallel updates won't cause data loss. This isn't maintained by `fresh_context` so it will need to be applied afterwards.
2023-11-22T21:12:20
ckan/ckan
7,939
ckan__ckan-7939
[ "7565" ]
b4f901486a343f9ab37fa754bc0a3f2f75d1354b
diff --git a/ckan/lib/maintain.py b/ckan/lib/maintain.py --- a/ckan/lib/maintain.py +++ b/ckan/lib/maintain.py @@ -3,6 +3,7 @@ ''' This module contains code that helps in maintaining the Ckan codebase. ''' from __future__ import annotations +import functools import inspect import time import logging @@ -41,6 +42,7 @@ def decorator(fn: Callable[P, RT]) -> Callable[P, RT]: 'It must include the word `deprecated`.' % (fn.__name__, fn.__module__)) + @functools.wraps(fn) def wrapped(*args: P.args, **kw: P.kwargs) -> RT: since_msg = f'since CKAN v{since}' if since else '' msg = (
`truncate` helper is deprecated, but does not work ## CKAN version 2.10.0 ## Describe the bug `truncate` helper is deprecated, but does not work ### Steps to reproduce - Try to use `h.truncate` in a template - Load the page - `ckan.exceptions.HelperError: Helper 'truncate' has not been defined.` ### Expected behavior - No crash ### Additional details Swapping the order of decorators `maintain.deprecated` and `core_helper` fixes the issue.
Hi @wardi I tried using "h.truncate" in an HTML file of CKAN 2.10.0, and the issue was reproduced. I would like to work on this issue.
2023-11-24T13:10:28
ckan/ckan
7,947
ckan__ckan-7947
[ "7945" ]
32957910927b9c5331963eef2376f6df4c39214b
diff --git a/ckan/cli/generate.py b/ckan/cli/generate.py --- a/ckan/cli/generate.py +++ b/ckan/cli/generate.py @@ -4,7 +4,7 @@ import contextlib import os import json -from packaging.version import parse as version_parse +from packaging.version import Version import shutil from typing import Optional @@ -90,8 +90,7 @@ def extension(output_dir: str): include_examples = int(click.confirm( "Do you want to include code examples?")) - - full_ckan_version = version_parse(ckan.__version__) + full_ckan_version: Version = Version(ckan.__version__) ckan_version = f"{full_ckan_version.major}.{full_ckan_version.minor}" context = {
aria-labels without translations ## CKAN version 2.10 ## Describe the bug There are some aria-labels that are not covered by the translations, causing a mis-match in the UI language for people that are using screen readers. ### Steps to reproduce Using a CKAN instance with a German localization (100% translated according to transifex), such as https://opendata.leipzig.de: - shrink screen to "smartphone" size: Navigation menu button is labeled "Toggle navigation" - [hardcoded here](https://github.com/ckan/ckan/blob/9acb5af18fdbc6d084606be399837f680b49b634/ckan/templates/header.html#L92) - fail to log in, error message close button is labeled "Close" - [probably a recurring issue](https://github.com/search?q=repo%3Ackan%2Fckan+aria-label%3D%22Close%22&type=code) ### Expected behavior Navigation elements have localized labels. ## Comments I might expand this list if more missing label translations are found. I'm also looking into transifex and whether I can get this fixed myself.
Thanks for this @toothstone , the strings you point to won't appear in Transifex because they should be wrapped with the translation function `_` so they are extracted. For html templates it's easy: ```diff diff --git a/ckan/templates/header.html b/ckan/templates/header.html index 610e6eb85..48989501f 100644 --- a/ckan/templates/header.html +++ b/ckan/templates/header.html @@ -89,7 +89,7 @@ </hgroup> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#main-navigation-toggle" - aria-controls="main-navigation-toggle" aria-expanded="false" aria-label="Toggle navigation"> + aria-controls="main-navigation-toggle" aria-expanded="false" aria-label="{{ _('Toggle navigation') }}"> <span class="fa fa-bars text-white"></span> </button> ``` For JS modules is a bit more tricky but definitely worth doing. There are a few attributes that need to be fixed (`grep -r 'aria-label="[^{]' ckan ckanext`) but I'll submit a PR soon. Once this is merged and backported to the `dev-v2.10` we will extract the new messages and upload them to Transifex, so if you register there you'll be able to add the German translation for it, which will be included in 2.10.2.
2023-11-28T14:29:38
ckan/ckan
7,948
ckan__ckan-7948
[ "7931" ]
6692e0b748866e8d0ff24704190454b5c5eafa6a
diff --git a/ckan/views/resource.py b/ckan/views/resource.py --- a/ckan/views/resource.py +++ b/ckan/views/resource.py @@ -94,7 +94,7 @@ def read(package_type: str, id: str, resource_id: str) -> Union[Response, str]: try: package[u'isopen'] = model.Package.get_license_register()[license_id ].isopen() - except KeyError: + except (KeyError, AttributeError): package[u'isopen'] = False resource_views = get_action(u'resource_view_list')(
Catch AttributeErrors in license retrieval The following code segment may also result in an `AttributeError`: https://github.com/ckan/ckan/blob/8ddc2e800793d683c856b4a56f3d3f0ad3f1d168/ckan/views/resource.py#L95-L96 If, for some reason, the license object returned by `model.Package.get_license_register()[license_id]` does not have an `isopen` attribute or method, trying to call `isopen()` would result in an `AttributeError`, as well if `model.Package.get_license_register()[license_id]` evaluates to `None`. Currently, only `KeyErrors` are being caught. It is advisable to include `AttributeError` in the except handle of the try block: ```python except (KeyError, AttributeError): package[u'isopen'] = False ```
@amercader @thorge , I am interested to work on this issue. I will submit a PR.
2023-11-29T06:21:10
ckan/ckan
8,093
ckan__ckan-8093
[ "8092" ]
3b3ac6a2d8e990293a3d274ce75ac0013fc750d1
diff --git a/doc/conf.py b/doc/conf.py --- a/doc/conf.py +++ b/doc/conf.py @@ -85,7 +85,9 @@ extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinx.ext.autosummary', 'ckan.plugins.toolkit_sphinx_extension', + 'sphinx_rtd_theme', ] +html_theme = 'sphinx_rtd_theme' autodoc_member_order = 'bysource' todo_include_todos = True
readthedocs sphinx build failures ## CKAN version master ## Describe the bug infinite loop in build, looks like no tags are returned from `git log`? ### Steps to reproduce check sphinx logs ### Expected behavior build docs on rtd working ### Additional details ```python-traceback Traceback (most recent call last): File "/home/docs/checkouts/readthedocs.org/user_builds/ckan/envs/latest/lib/python3.10/site-packages/sphinx/config.py", line 358, in eval_config_file exec(code, namespace) # NoQA: S102 File "/home/docs/checkouts/readthedocs.org/user_builds/ckan/checkouts/latest/doc/conf.py", line 388, in <module> current_release_tag_value = get_current_release_tag() File "/home/docs/checkouts/readthedocs.org/user_builds/ckan/checkouts/latest/doc/conf.py", line 211, in get_current_release_tag return get_latest_release_tag() File "/home/docs/checkouts/readthedocs.org/user_builds/ckan/checkouts/latest/doc/conf.py", line 228, in get_latest_release_tag return get_latest_release_version() File "/home/docs/checkouts/readthedocs.org/user_builds/ckan/checkouts/latest/doc/conf.py", line 237, in get_latest_release_version version = get_latest_release_tag()[len('ckan-'):] File "/home/docs/checkouts/readthedocs.org/user_builds/ckan/checkouts/latest/doc/conf.py", line 228, in get_latest_release_tag return get_latest_release_version() File "/home/docs/checkouts/readthedocs.org/user_builds/ckan/checkouts/latest/doc/conf.py", line 237, in get_latest_release_version version = get_latest_release_tag()[len('ckan-'):] … ```
2024-02-28T20:41:26
ckan/ckan
8,100
ckan__ckan-8100
[ "8097" ]
a1a8f1c70981e7778b5e7d6e7dc4dd86d3c4638a
diff --git a/ckan/plugins/interfaces.py b/ckan/plugins/interfaces.py --- a/ckan/plugins/interfaces.py +++ b/ckan/plugins/interfaces.py @@ -283,7 +283,7 @@ def info(self) -> dict[str, Any]: :returns: a dictionary with the view type configuration :rtype: dict - .. _Font Awesome: http://fortawesome.github.io/Font-Awesome/3.2.1/icons + .. _Font Awesome: https://fontawesome.com/search ''' return {u'name': self.__class__.__name__}
Broken Link for Font Awesome in Documentation ## CKAN version latest ## Describe the bug Documentation update https://github.com/ckan/ckan/blob/3b3ac6a2d8e990293a3d274ce75ac0013fc750d1/ckan/plugins/interfaces.py#L286 Contains a link that produces a 404 while also looking like it references a very old version of FA. Happy to submit a PR, but am unsure if better to link to https://fontawesome.com or https://github.com/FortAwesome/Font-Awesome and if a specific version should be referenced.
Either is fine @pdekraker-epa let's drop the version, a PR would be great!
2024-03-05T14:02:43
ckan/ckan
8,110
ckan__ckan-8110
[ "8108" ]
6992ec2e9ad0e1d3f271b200baefa735c9fa5d9f
diff --git a/ckanext/datastore/backend/postgres.py b/ckanext/datastore/backend/postgres.py --- a/ckanext/datastore/backend/postgres.py +++ b/ckanext/datastore/backend/postgres.py @@ -2315,7 +2315,12 @@ def resource_fields(self, id: str) -> dict[str, Any]: info['meta']['aliases'] = aliases # get the data dictionary for the resource - data_dictionary = datastore_helpers.datastore_dictionary(id) + with engine.connect() as conn: + data_dictionary = _result_fields( + _get_fields_types(conn, id), + _get_field_info(conn, id), + None + ) schema_sql = sa.text(f''' SELECT @@ -2361,6 +2366,8 @@ def resource_fields(self, id: str) -> dict[str, Any]: schemainfo[colname] = colinfo for field in data_dictionary: + if field['id'].startswith('_'): + continue field.update({'schema': schemainfo[field['id']]}) info['fields'].append(field) diff --git a/ckanext/datastore/helpers.py b/ckanext/datastore/helpers.py --- a/ckanext/datastore/helpers.py +++ b/ckanext/datastore/helpers.py @@ -216,11 +216,8 @@ def datastore_dictionary( """ try: return [ - f for f in tk.get_action('datastore_search')( - {}, { - u'resource_id': resource_id, - u'limit': 0, - u'include_total': False})['fields'] + f for f in tk.get_action('datastore_info')( + {}, {'id': resource_id})['fields'] if not f['id'].startswith(u'_') and ( include_columns is None or f['id'] in include_columns) ]
Custom Data Dictionary preview ## CKAN version master ## Describe the bug IDataDictionaryForm lets us expand on the data dictionary form and validation but not the Data Dictionary preview in the resource pages ### Steps to reproduce Use IDataDictionaryForm to add fields to the data dictionary. ### Expected behavior New fields should be visible in the resource page, not only the DataStore types, labels and descriptions ### Additional details
2024-03-11T15:21:44
ckan/ckan
8,186
ckan__ckan-8186
[ "8179" ]
4da81ee6b07b4b5b522f1ca4ad8e84f05bccb5ed
diff --git a/ckan/logic/action/patch.py b/ckan/logic/action/patch.py --- a/ckan/logic/action/patch.py +++ b/ckan/logic/action/patch.py @@ -24,12 +24,10 @@ def package_patch( parameters unchanged, whereas the update methods deletes all parameters not explicitly provided in the data_dict. - You are able to partially update and/or create resources with - package_patch. If you are updating existing resources be sure to provide - the resource id. Existing resources excluded from the package_patch - data_dict will be removed. Resources in the package data_dict without - an id will be treated as new resources and will be added. New resources - added with the patch method do not create the default views. + To partially update resources or other metadata not at the top level + of a package use + :py:func:`~ckan.logic.action.update.package_revise` instead to maintain + existing nested values. You must be authorized to edit the dataset and the groups that it belongs to.
package_patch breaks uploaded resources ## CKAN version 2.10.4 ## Describe the bug When using package_patch to update a dataset, intending **not** to update an uploaded resource the resource filename appears to be lost ### Steps to reproduce 1. Create a dataset containing at least one uploaded file resource 2. Call package_patch to update the dataset, but for the resources only pass the resource ids like specified in the documentation (https://docs.ckan.org/en/2.10/api/#ckan.logic.action.patch.package_patch) like: ``` package_patch(**{'id':'b6cc8622-3334-4cdb-8960-e2a3c4269a8d', 'description':'Updated description', 'resources':[{'id':'a97b8889-5efb-440c-b6ad-fa9a9e4d7659'}, {'id':'bdbb977f-9faa-4715-88d3-c5e9042e69a4', 'description':'Updated resource description'}]}) ``` 3. Browse to the updated resource, the download link is missing the file name probably replaced by ___ and the mimetype is lost ### Expected behavior The resources should be unchanged when no changes are requested ### Additional details I think part of this issue arises out of url being used to store the filename. It may be cleaner to just add filename as another field in uploaded resources which could also make renaming uploaded files easier.
Thanks @pdekraker-epa the `package_patch` docs added by https://github.com/ckan/ckan/pull/4563 are incorrect. I'll create a PR to remove them. `package_patch` has no understanding of the package/resource structure and instead simply replaces any keys passed (including `resources`) through to `package_update`. If you want to update some fields at the dataset level and other fields at the resource level you can use `package_revise` instead which lets you replace specific fields at any level of nesting without disturbing other existing fields.
2024-04-17T14:20:20
ckan/ckan
8,236
ckan__ckan-8236
[ "8235" ]
5334babe3888a239dea15a17c8af8e46d1c3f346
diff --git a/ckan/cli/db.py b/ckan/cli/db.py --- a/ckan/cli/db.py +++ b/ckan/cli/db.py @@ -41,6 +41,18 @@ def init(): click.secho(u'Initialising DB: SUCCESS', fg=u'green', bold=True) [email protected]() +def create_from_model(): + """Initialize database from the model instead of migrations. + """ + try: + model.repo.create_db() + except Exception as e: + error_shout(e) + else: + click.secho('Create DB from model: SUCCESS', fg='green', bold=True) + + PROMPT_MSG = u'This will delete all of your data!\nDo you want to continue?'
missing ckan db create-from-model ## CKAN version master, 2.10, 2.9 ## Describe the bug Documented `ckan db create-from-model` command https://docs.ckan.org/en/2.10/contributing/database-migrations.html#manual-checking doesn't exist. ### Steps to reproduce Follow steps in database migrations document ### Expected behavior ### Additional details Seems to have been removed in migration to click cli
2024-05-23T12:39:01
litestar-org/litestar
38
litestar-org__litestar-38
[ "31" ]
93ee4cdbc596dbd0c29a534cc3e5e71eae954589
diff --git a/starlite/controller.py b/starlite/controller.py --- a/starlite/controller.py +++ b/starlite/controller.py @@ -41,7 +41,7 @@ class Controller: after_request: Optional[AFTER_REQUEST_HANDLER] def __init__(self, owner: "Router"): - if not hasattr(self, "path") or not self.path: + if not hasattr(self, "path") or self.path is None: raise ImproperlyConfiguredException("Controller subclasses must set a path attribute") for key in [ @@ -55,7 +55,9 @@ def __init__(self, owner: "Router"): if not hasattr(self, key): setattr(self, key, None) - self.path = normalize_path(self.path) + if self.path: + self.path = normalize_path(self.path) + self.owner = owner for route_handler in self.get_route_handlers(): route_handler.owner = self
diff --git a/tests/test_controller.py b/tests/test_controller.py --- a/tests/test_controller.py +++ b/tests/test_controller.py @@ -7,6 +7,7 @@ HTTP_200_OK, HTTP_201_CREATED, HTTP_204_NO_CONTENT, + HTTP_404_NOT_FOUND, HTTP_500_INTERNAL_SERVER_ERROR, ) @@ -275,3 +276,59 @@ async def ws(self, socket: WebSocket) -> None: ws.send_json({"data": "123"}) data = ws.receive_json() assert data + + [email protected]( + "decorator, http_method, expected_status_code, test_path", + [ + (get, HttpMethod.GET, HTTP_200_OK, ""), + (post, HttpMethod.POST, HTTP_201_CREATED, ""), + (put, HttpMethod.PUT, HTTP_200_OK, ""), + (patch, HttpMethod.PATCH, HTTP_200_OK, ""), + (delete, HttpMethod.DELETE, HTTP_204_NO_CONTENT, ""), + (get, HttpMethod.GET, HTTP_200_OK, "/"), + (post, HttpMethod.POST, HTTP_201_CREATED, "/"), + (put, HttpMethod.PUT, HTTP_200_OK, "/"), + (patch, HttpMethod.PATCH, HTTP_200_OK, "/"), + (delete, HttpMethod.DELETE, HTTP_204_NO_CONTENT, "/"), + ], +) +def test_controller_empty_path(decorator, http_method, expected_status_code, test_path): + class MyController(Controller): + path = test_path + + @decorator(path="/something") + def test_method(self) -> Person: + return person_instance + + with create_test_client(MyController) as client: + response = client.request(http_method, test_path + "/something") + assert response.status_code == expected_status_code + assert response.json() == person_instance.dict() + + [email protected]( + "decorator, http_method, expected_status_code", + [ + (get, HttpMethod.GET, HTTP_200_OK), + (post, HttpMethod.POST, HTTP_201_CREATED), + (put, HttpMethod.PUT, HTTP_200_OK), + (patch, HttpMethod.PATCH, HTTP_200_OK), + (delete, HttpMethod.DELETE, HTTP_204_NO_CONTENT), + ], +) +def test_controller_empty_path_root_endpoint(decorator, http_method, expected_status_code): + class MyController(Controller): + path = "" + + @decorator(path="/") + def test_method(self) -> Person: + return person_instance + + with create_test_client(MyController) as client: + response = client.request(http_method, "/") + assert response.status_code == expected_status_code + assert response.json() == person_instance.dict() + + response = client.request(http_method, "") + assert response.status_code == HTTP_404_NOT_FOUND
allow empty `""` path in Controller ? https://github.com/starlite-api/starlite/blob/965d97620774991bd302a3a227bd3ebe6236ae96/starlite/controller.py#L27-L28 ### Context In some of our project (built with FastAPI) we use **Factory** classes that helps us creating bunch of endpoints for given user inputs and dependencies (https://developmentseed.org/titiler/advanced/tiler_factories/ https://developmentseed.org/titiler/api/titiler/core/factory/#tilerfactory). This is why I was really interested in the `Controller` class to replace our `Factories`. One problem I'm facing right now is that Controller `Path` has to be non null. ```python from starlite import get, Starlite from starlite.controller import Controller from starlette.requests import Request class Endpoints(Controller): """TileMatrixSets endpoints.""" path = "/" @get(path="/yo") def hey(self, request: Request) -> str: return "yipi" @get(path="ye") def hey2(self, request: Request) -> str: return "what" app = Starlite(route_handlers=[Endpoints]) ``` schema <details> ```json { "openapi": "3.1.0", "info": { "title": "Starlite API", "version": "1.0.0" }, "servers": [ { "url": "/" } ], "paths": { "//yo": { "get": { "operationId": "hey", "responses": { "200": { "description": "Request fulfilled, document follows", "headers": {}, "content": { "application/json": { "schema": { "type": "string" } } } } }, "deprecated": false } }, "//ye": { "get": { "operationId": "hey2", "responses": { "200": { "description": "Request fulfilled, document follows", "headers": {}, "content": { "application/json": { "schema": { "type": "string" } } } } }, "deprecated": false } } } } ``` </details> as we can see in the schema ☝️, both endpoints are `//` prefixed because Starlite is normalizing path (I think). I can agree that I want to use the Controller class for something it wasn't designed for, but it could be nice if the `path` could be set to `""`. ### Potential fix By allowing path to be all but not `None` it seem to fix my issue, but I'm not quite sure what it means for the rest of the application. ```python class Endpoints(Controller): """TileMatrixSets endpoints.""" path = "" def __init__(self, owner: "Router"): if not hasattr(self, "path") or self.path is None: raise ImproperlyConfiguredException("Controller subclasses must set a path attribute") for key in ["dependencies", "response_headers", "response_class", "guards"]: if not hasattr(self, key): setattr(self, key, None) self.path = self.path self.owner = owner for route_handler in self.get_route_handlers(): route_handler.owner = self @get(path="/yo") def hey(self, request: Request) -> str: print(request) return "yipi" @get(path="/ye") def hey2(self, request: Request) -> str: print(request) return "what" ``` again, I will understand that I want to use the Controller class outside of its scope 🙏
Hiya. If I understand you correctly you would.in effect like to use a controller on the root level, correct? If that is the case then I'd say we have a bug - you should be able to do: `path = "/"` If this results in //, we need to fix it. If I misunderstood though: How about this solution: 1. We move the validation to a method that is called by `Controller.__init__`. 2. You can then override it in your subclass. In either case, would you like to add a PR with a fix (and changelog update)? > If I understand you correctly you would.in effect like to use a controller on the root level, correct? Yes. > If this results in //, we need to fix it. It does (see schema) > In either case, would you like to add a PR with a fix (and changelog update)? I can try, later today or tomorrow 😄 @Goldziher I'm not quite sure of the solution here. ## Case 1: `path = ""` This is quite straight forward, meaning that routes won't have any prefix. This also ensure the user set `""` as the path and that we will only raise is path is not set at all. We could just add a note in the documentation (or a warning in the code) that `""` path will append routes at the root. ## Case 2: `path = "/"` This could cause some misunderstanding. To me all routes should be prefixed with `/` (I believe `//yo` is a valid path 🤷. Sure, path 1 is good. Just add a note on the docs as well. Maybe raise an informative error if the path is set to "/" by the user, or also allow that case.
2022-01-17T13:08:57
litestar-org/litestar
95
litestar-org__litestar-95
[ "77" ]
c1c9e49a591be0cdbe07d8dd0559cf604c1b8154
diff --git a/starlite/__init__.py b/starlite/__init__.py --- a/starlite/__init__.py +++ b/starlite/__init__.py @@ -44,6 +44,7 @@ from .params import Body, Parameter from .plugins import PluginProtocol from .provide import Provide +from .queue_listener_handler import QueueListenerHandler from .response import Response from .routing import BaseRoute, HTTPRoute, Router, WebSocketRoute from .testing import TestClient, create_test_client, create_test_request @@ -96,6 +97,7 @@ "Template", "TemplateConfig", "TestClient", + "QueueListenerHandler", "ValidationException", "WebSocket", "WebSocketRoute", diff --git a/starlite/logging.py b/starlite/logging.py --- a/starlite/logging.py +++ b/starlite/logging.py @@ -14,12 +14,13 @@ class LoggingConfig(BaseModel): "standard": {"format": "%(levelname)s - %(asctime)s - %(name)s - %(module)s - %(message)s"} } handlers: Dict[str, Dict[str, Any]] = { - "console": {"class": "logging.StreamHandler", "level": "DEBUG", "formatter": "standard"} + "console": {"class": "logging.StreamHandler", "level": "DEBUG", "formatter": "standard"}, + "queue_listener": {"class": "starlite.QueueListenerHandler", "handlers": ["cfg://handlers.console"]}, } loggers: Dict[str, Dict[str, Any]] = { "starlite": { "level": "INFO", - "handlers": ["console"], + "handlers": ["queue_listener"], }, } root: Dict[str, Union[Dict[str, Any], List[Any], str]] = {"handlers": ["console"], "level": "WARNING"} diff --git a/starlite/queue_listener_handler.py b/starlite/queue_listener_handler.py new file mode 100644 --- /dev/null +++ b/starlite/queue_listener_handler.py @@ -0,0 +1,46 @@ +from atexit import register +from logging.config import ConvertingList # type: ignore +from logging.handlers import QueueHandler, QueueListener +from queue import Queue +from typing import List + + +def _resolve_handlers(handlers: List[str]) -> List: + """ + Converts list of string of handlers to the object of respective handler. + Indexing the list performs the evaluation of the object. + """ + if not isinstance(handlers, ConvertingList): + return handlers + + return [handlers[i] for i in range(len(handlers))] + + +class QueueListenerHandler(QueueHandler): + """ + Configures queue listener and handler to support non-blocking logging configuration. + """ + + def __init__( + self, handlers: List, respect_handler_level: bool = False, auto_run: bool = True, queue: Queue = Queue(-1) + ): + super().__init__(queue) + self.handlers = _resolve_handlers(handlers) + self._listener: QueueListener = QueueListener( + self.queue, *self.handlers, respect_handler_level=respect_handler_level + ) + if auto_run: + self.start() + register(self.stop) + + def start(self) -> None: + """ + starts the listener. + """ + self._listener.start() + + def stop(self) -> None: + """ + Manually stop a listener. + """ + self._listener.stop()
diff --git a/tests/queue_handler/__init__.py b/tests/queue_handler/__init__.py new file mode 100644 diff --git a/tests/queue_handler/test_queue_handler.py b/tests/queue_handler/test_queue_handler.py new file mode 100644 --- /dev/null +++ b/tests/queue_handler/test_queue_handler.py @@ -0,0 +1,27 @@ +import logging +from logging import StreamHandler + +from _pytest.logging import LogCaptureFixture + +from starlite.logging import LoggingConfig + +config = LoggingConfig(root={"handlers": ["queue_listener"], "level": "WARNING"}) +config.configure() +logger = logging.getLogger() + + +def test_logger(caplog: LogCaptureFixture) -> None: + """ + Test to check logging output contains the logged message + """ + caplog.set_level(logging.INFO) + logger.info("Testing now!") + assert "Testing now!" in caplog.text + + +def test_resolve_handler() -> None: + """ + Tests resolve handler + """ + handlers = logger.handlers + assert isinstance(handlers[0].handlers[0], StreamHandler) # type: ignore
[enhancement] logging setup to be non-blocking The default logging config, which is just a simple abstraction on top of DictConfig, creates a standard python logger. The issue with this setup is that python logging is sync and blocking. This means that the logging config needs to be updated to setup a QueueHandler. Here are some resources regarding this: 1. https://rob-blackbourn.medium.com/how-to-use-python-logging-queuehandler-with-dictconfig-1e8b1284e27a 2. https://stackoverflow.com/questions/25585518/python-logging-logutils-with-queuehandler-and-queuelistener 3. https://betterprogramming.pub/power-up-your-python-logging-6dd3ed38f322
We use [this](https://python-logstash-async.readthedocs.io/en/stable/) library with logstash, it's awesome. Hello, I would like to contribute and work on this issue. > Hello, I would like to contribute and work on this issue. Great, looking forward to your PR 😃
2022-02-21T18:38:58
litestar-org/litestar
168
litestar-org__litestar-168
[ "167" ]
7211dee1db3ac347b83e5199c6b89606251fffa7
diff --git a/starlite/app.py b/starlite/app.py --- a/starlite/app.py +++ b/starlite/app.py @@ -283,7 +283,7 @@ def default_http_exception_handler(self, request: Request, exc: Exception) -> St server_middleware = ServerErrorMiddleware(app=self) return server_middleware.debug_response(request=request, exc=exc) if isinstance(exc, HTTPException): - content = {"detail": exc.detail, "extra": exc.extra} + content = {"detail": exc.detail, "extra": exc.extra, "status_code": exc.status_code} elif isinstance(exc, StarletteHTTPException): content = {"detail": exc.detail} else: diff --git a/starlite/openapi/responses.py b/starlite/openapi/responses.py --- a/starlite/openapi/responses.py +++ b/starlite/openapi/responses.py @@ -125,7 +125,9 @@ def create_error_responses(exceptions: List[Type[HTTPException]]) -> Iterator[Tu properties=dict( status_code=Schema(type=OpenAPIType.INTEGER), detail=Schema(type=OpenAPIType.STRING), - extra=Schema(type=OpenAPIType.OBJECT, additionalProperties=Schema()), + extra=Schema( + type=[OpenAPIType.NULL, OpenAPIType.OBJECT, OpenAPIType.ARRAY], additionalProperties=Schema() + ), ), description=pascal_case_to_text(get_name(exc)), examples=[{"status_code": status_code, "detail": HTTPStatus(status_code).phrase, "extra": {}}],
diff --git a/tests/app/test_error_handling.py b/tests/app/test_error_handling.py --- a/tests/app/test_error_handling.py +++ b/tests/app/test_error_handling.py @@ -27,6 +27,40 @@ def test_default_handle_http_exception_handling() -> None: assert json.loads(response.body) == { "detail": "starlite_exception", "extra": {"key": "value"}, + "status_code": 500, + } + + response = Starlite(route_handlers=[]).default_http_exception_handler( + Request(scope={"type": "http", "method": "GET"}), + HTTPException(detail="starlite_exception"), + ) + assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR + assert json.loads(response.body) == { + "detail": "starlite_exception", + "extra": None, + "status_code": 500, + } + + response = Starlite(route_handlers=[]).default_http_exception_handler( + Request(scope={"type": "http", "method": "GET"}), + HTTPException(detail="starlite_exception", extra=None), + ) + assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR + assert json.loads(response.body) == { + "detail": "starlite_exception", + "extra": None, + "status_code": 500, + } + + response = Starlite(route_handlers=[]).default_http_exception_handler( + Request(scope={"type": "http", "method": "GET"}), + HTTPException(detail="starlite_exception", extra=["extra-1", "extra-2"]), + ) + assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR + assert json.loads(response.body) == { + "detail": "starlite_exception", + "extra": ["extra-1", "extra-2"], + "status_code": 500, } response = Starlite(route_handlers=[]).default_http_exception_handler( diff --git a/tests/test_template.py b/tests/test_template.py --- a/tests/test_template.py +++ b/tests/test_template.py @@ -52,7 +52,7 @@ def invalid_path() -> Template: ) as client: response = client.request("GET", "/") assert response.status_code == 500 - assert response.json() == {"detail": "Template invalid.html not found.", "extra": None} + assert response.json() == {"detail": "Template invalid.html not found.", "extra": None, "status_code": 500} def test_mako_template(tmpdir: Any) -> None: @@ -101,7 +101,7 @@ def invalid_path() -> Template: ) as client: response = client.request("GET", "/") assert response.status_code == 500 - assert response.json() == {"detail": "Template invalid.html not found.", "extra": None} + assert response.json() == {"detail": "Template invalid.html not found.", "extra": None, "status_code": 500} def test_handler_raise_for_no_template_engine() -> None: @@ -112,7 +112,7 @@ def invalid_path() -> Template: with create_test_client(route_handlers=[invalid_path]) as client: response = client.request("GET", "/") assert response.status_code == 500 - assert response.json() == {"detail": "Template engine is not configured", "extra": None} + assert response.json() == {"detail": "Template engine is not configured", "extra": None, "status_code": 500} def test_template_with_no_context(tmpdir: Any) -> None:
OpenAPI schema generation includes `status_code` but default exception handler never outputs that attribute I was doing some endpoint schema validation for my project and ran into what seems like an inconsistency between the generated OpenAPI schema and reality. Specifically, `HTTPException` has an (optional) `status_code` attribute which is typically set to the response status code when something exceptional happens. The fact that this field should always be present in the output is documented in the generated schema, but in the code it is omitted in all cases in the default exception handler: ```py if isinstance(exc, HTTPException): content = {"detail": exc.detail, "extra": exc.extra} ``` This currently makes my tests fail because the schema says status_code is required, but starlite will never output it. There are two possible fixes for this: 1. Fix the OpenAPI schema generator not to include the field as required (or at all) 2. Update the default exception handler to include the field when it exists
So, whats your suggestion for a fix? I would go with updating the error handler. If you want, add a PR Personally I would go with option 2 because: - The status codes are already tracked and it's documented in all schemas that Starlite has generated up until now, so this would break the "API" less in the sense that the OpenAPI schema just becomes more truthful instead of changing. - The status code is always given in `HTTPException` (500 by default) so we can simply add the field in the default exception handler and fix this very easily. It will be 500 when not otherwise specified and if it *is* specified, it'll be whatever the developer put in, which is expected behavior based on the rest of Starlite.
2022-06-23T11:45:17
litestar-org/litestar
172
litestar-org__litestar-172
[ "170" ]
021c95f5bae7f596c44e72aef18324480f431c0b
diff --git a/starlite/app.py b/starlite/app.py --- a/starlite/app.py +++ b/starlite/app.py @@ -36,7 +36,6 @@ from starlite.router import Router from starlite.routes import ASGIRoute, BaseRoute, HTTPRoute, WebSocketRoute from starlite.signature import model_function_signature -from starlite.template import TemplateEngineProtocol from starlite.types import ( AfterRequestHandler, BeforeRequestHandler, @@ -49,6 +48,7 @@ ) from starlite.utils import normalize_path from starlite.utils.exception import get_exception_handler +from starlite.utils.templates import create_template_engine DEFAULT_OPENAPI_CONFIG = OpenAPIConfig(title="Starlite API", version="1.0.0") DEFAULT_CACHE_CONFIG = CacheConfig() @@ -134,10 +134,7 @@ def __init__( static_files = StaticFiles(html=config.html_mode, check_dir=False) static_files.all_directories = config.directories # type: ignore self.register(asgi(path=path)(static_files)) - if template_config: - self.template_engine: Optional[TemplateEngineProtocol] = template_config.engine(template_config.directory) - else: - self.template_engine = None + self.template_engine = create_template_engine(template_config) async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: scope["app"] = self diff --git a/starlite/config.py b/starlite/config.py --- a/starlite/config.py +++ b/starlite/config.py @@ -1,4 +1,4 @@ -from typing import Any, Dict, List, Optional, Tuple, Union +from typing import Any, Callable, Dict, List, Optional, Tuple, Union from urllib.parse import urlencode from openapi_schema_pydantic import ( @@ -84,6 +84,7 @@ class Config: directory: Union[DirectoryPath, List[DirectoryPath]] engine: Type[TemplateEngineProtocol] + engine_callback: Optional[Callable[[Any], Any]] def default_cache_key_builder(request: Request) -> str: diff --git a/starlite/utils/templates.py b/starlite/utils/templates.py new file mode 100644 --- /dev/null +++ b/starlite/utils/templates.py @@ -0,0 +1,27 @@ +from typing import TYPE_CHECKING, Optional + +if TYPE_CHECKING: # pragma: no cover + from starlite.config import TemplateConfig + from starlite.template import TemplateEngineProtocol + + +def create_template_engine(template_config: Optional["TemplateConfig"]) -> Optional["TemplateEngineProtocol"]: + """ + Construct a template engine if `template_config` is provided. + + Parameters + ---------- + template_config : TemplateConfig | None + + Returns + ------- + TemplateEngineProtocol | None + """ + template_engine: Optional["TemplateEngineProtocol"] + if template_config: + template_engine = template_config.engine(template_config.directory) + if template_config.engine_callback is not None: + template_config.engine_callback(template_engine) + else: + template_engine = None + return template_engine
diff --git a/tests/template/__init__.py b/tests/template/__init__.py new file mode 100644 diff --git a/tests/template/conftest.py b/tests/template/conftest.py new file mode 100644 --- /dev/null +++ b/tests/template/conftest.py @@ -0,0 +1,8 @@ +import pathlib + +import pytest + + [email protected] +def template_dir(tmp_path: pathlib.Path) -> pathlib.Path: + return tmp_path diff --git a/tests/template/test_built_in.py b/tests/template/test_built_in.py new file mode 100644 --- /dev/null +++ b/tests/template/test_built_in.py @@ -0,0 +1,108 @@ +import pathlib +from dataclasses import dataclass +from typing import Any, Type, Union + +import pytest + +from starlite import HTTPRouteHandler, Template, TemplateConfig, get +from starlite.template.jinja import JinjaTemplateEngine +from starlite.template.mako import MakoTemplateEngine +from starlite.testing import create_test_client + + +@dataclass +class EngineTest: + engine: Type[Union[JinjaTemplateEngine, MakoTemplateEngine]] + index_template: str + nested_template: str + + [email protected]( + params=[ + EngineTest( + engine=JinjaTemplateEngine, + index_template="<html>Injected? {{test}}</html>", + nested_template="<html>Does nested dirs work? {{test}}</html>", + ), + EngineTest( + engine=MakoTemplateEngine, + index_template="<html>Injected? ${test}</html>", + nested_template="<html>Does nested dirs work? ${test}</html>", + ), + ] +) +def engine_test(request: Any) -> EngineTest: + return request.param # type:ignore[no-any-return] + + [email protected] +def index_handler(engine_test: EngineTest, template_dir: pathlib.Path) -> HTTPRouteHandler: + with open(template_dir / "index.html", "w") as f: + f.write(engine_test.index_template) + + @get(path="/") + def index_handler() -> Template: + return Template(name="index.html", context={"test": "yep"}) + + return index_handler + + [email protected] +def nested_path_handler(engine_test: EngineTest, template_dir: pathlib.Path) -> HTTPRouteHandler: + nested_path = template_dir / "nested-dir" + nested_path.mkdir() + with open(nested_path / "nested.html", "w") as f: + f.write(engine_test.nested_template) + + @get(path="/nested") + def nested_path_handler() -> Template: + return Template(name="nested-dir/nested.html", context={"test": "yep"}) + + return nested_path_handler + + [email protected] +def template_config(engine_test: EngineTest, template_dir: pathlib.Path) -> TemplateConfig: + return TemplateConfig(engine=engine_test.engine, directory=template_dir) + + +def test_template(index_handler: HTTPRouteHandler, template_config: TemplateConfig) -> None: + with create_test_client(route_handlers=[index_handler], template_config=template_config) as client: + response = client.request("GET", "/") + assert response.status_code == 200, response.text + assert response.text == "<html>Injected? yep</html>" + assert response.headers["Content-Type"] == "text/html; charset=utf-8" + + +def test_nested_template_directory(nested_path_handler: HTTPRouteHandler, template_config: TemplateConfig) -> None: + with create_test_client(route_handlers=[nested_path_handler], template_config=template_config) as client: + response = client.request("GET", "/nested") + assert response.status_code == 200, response.text + assert response.text == "<html>Does nested dirs work? yep</html>" + assert response.headers["Content-Type"] == "text/html; charset=utf-8" + + +def test_raise_for_invalid_template_name(template_config: TemplateConfig) -> None: + @get(path="/") + def invalid_template_name_handler() -> Template: + return Template(name="invalid.html", context={"test": "yep"}) + + with create_test_client(route_handlers=[invalid_template_name_handler], template_config=template_config) as client: + response = client.request("GET", "/") + assert response.status_code == 500 + assert response.json() == {"detail": "Template invalid.html not found.", "extra": None, "status_code": 500} + + +def test_no_context(template_dir: pathlib.Path, template_config: TemplateConfig) -> None: + with open(template_dir / "index.html", "w") as file: + file.write("<html>This works!</html>") + + @get(path="/") + def index() -> Template: + return Template(name="index.html") + + with create_test_client(route_handlers=[index], template_config=template_config) as client: + index_response = client.request("GET", "/") + assert index_response.status_code == 200 + assert index_response.text == "<html>This works!</html>" + assert index_response.headers["Content-Type"] == "text/html; charset=utf-8" diff --git a/tests/template/test_template.py b/tests/template/test_template.py new file mode 100644 --- /dev/null +++ b/tests/template/test_template.py @@ -0,0 +1,37 @@ +import pathlib + +from starlite import Starlite, Template, TemplateConfig, get +from starlite.template.jinja import JinjaTemplateEngine +from starlite.testing import create_test_client + + +def test_handler_raise_for_no_template_engine() -> None: + @get(path="/") + def invalid_path() -> Template: + return Template(name="index.html", context={"ye": "yeeee"}) + + with create_test_client(route_handlers=[invalid_path]) as client: + response = client.request("GET", "/") + assert response.status_code == 500 + assert response.json() == {"detail": "Template engine is not configured", "extra": None, "status_code": 500} + + +def test_engine_passed_to_callback(template_dir: pathlib.Path) -> None: + received_engine: JinjaTemplateEngine | None = None + + def callback(engine: JinjaTemplateEngine) -> JinjaTemplateEngine: + nonlocal received_engine + received_engine = engine + return engine + + app = Starlite( + route_handlers=[], + template_config=TemplateConfig( + directory=template_dir, + engine=JinjaTemplateEngine, + engine_callback=callback, + ), + ) + + assert received_engine is not None + assert received_engine is app.template_engine diff --git a/tests/test_template.py b/tests/test_template.py --- a/tests/test_template.py +++ b/tests/test_template.py @@ -1,135 +0,0 @@ -import os -from typing import Any - -from starlite import Template, TemplateConfig, get -from starlite.template.jinja import JinjaTemplateEngine -from starlite.template.mako import MakoTemplateEngine -from starlite.testing import create_test_client - - -def test_jinja_template(tmpdir: Any) -> None: - path = os.path.join(tmpdir, "index.html") - with open(path, "w") as file: - file.write("<html>Injected? {{test}}</html>") - - nested_dir = os.path.join(tmpdir, "users") - os.mkdir(nested_dir) - nested_path = os.path.join(nested_dir, "nested.html") - - with open(nested_path, "w") as file: - file.write("<html>Does nested dirs work? {{test}}</html>") - - @get(path="/") - def index_handler() -> Template: - return Template(name="index.html", context={"test": "yep"}) - - @get(path="/nested") - def nested_path_handler() -> Template: - return Template(name="users/nested.html", context={"test": "yep"}) - - with create_test_client( - route_handlers=[index_handler, nested_path_handler], - template_config=TemplateConfig(engine=JinjaTemplateEngine, directory=tmpdir), - ) as client: - index_response = client.request("GET", "/") - assert index_response.status_code == 200 - assert index_response.text == "<html>Injected? yep</html>" - assert index_response.headers["Content-Type"] == "text/html; charset=utf-8" - - nested_response = client.request("GET", "/nested") - assert nested_response.status_code == 200 - assert nested_response.text == "<html>Does nested dirs work? yep</html>" - assert nested_response.headers["Content-Type"] == "text/html; charset=utf-8" - - -def test_jinja_raise_for_invalid_path(tmpdir: Any) -> None: - @get(path="/") - def invalid_path() -> Template: - return Template(name="invalid.html", context={"test": "yep"}) - - with create_test_client( - route_handlers=[invalid_path], - template_config=TemplateConfig(engine=JinjaTemplateEngine, directory=tmpdir), - ) as client: - response = client.request("GET", "/") - assert response.status_code == 500 - assert response.json() == {"detail": "Template invalid.html not found.", "extra": None, "status_code": 500} - - -def test_mako_template(tmpdir: Any) -> None: - path = os.path.join(tmpdir, "index.html") - with open(path, "w") as file: - file.write("<html>Injected? ${test}</html>") - - nested_dir = os.path.join(tmpdir, "users") - os.mkdir(nested_dir) - nested_path = os.path.join(nested_dir, "nested.html") - - with open(nested_path, "w") as file: - file.write("<html>Does nested dirs work? ${test}</html>") - - @get(path="/") - def index_handler() -> Template: - return Template(name="index.html", context={"test": "yep"}) - - @get(path="/nested") - def nested_path_handler() -> Template: - return Template(name="users/nested.html", context={"test": "yep"}) - - with create_test_client( - route_handlers=[index_handler, nested_path_handler], - template_config=TemplateConfig(engine=MakoTemplateEngine, directory=tmpdir), - ) as client: - index_response = client.request("GET", "/") - assert index_response.status_code == 200 - assert index_response.text == "<html>Injected? yep</html>" - assert index_response.headers["Content-Type"] == "text/html; charset=utf-8" - - nested_response = client.request("GET", "/nested") - assert nested_response.status_code == 200 - assert nested_response.text == "<html>Does nested dirs work? yep</html>" - assert nested_response.headers["Content-Type"] == "text/html; charset=utf-8" - - -def test_mako_raise_for_invalid_path(tmpdir: Any) -> None: - @get(path="/") - def invalid_path() -> Template: - return Template(name="invalid.html", context={"test": "yep"}) - - with create_test_client( - route_handlers=[invalid_path], - template_config=TemplateConfig(engine=MakoTemplateEngine, directory=tmpdir), - ) as client: - response = client.request("GET", "/") - assert response.status_code == 500 - assert response.json() == {"detail": "Template invalid.html not found.", "extra": None, "status_code": 500} - - -def test_handler_raise_for_no_template_engine() -> None: - @get(path="/") - def invalid_path() -> Template: - return Template(name="index.html", context={"ye": "yeeee"}) - - with create_test_client(route_handlers=[invalid_path]) as client: - response = client.request("GET", "/") - assert response.status_code == 500 - assert response.json() == {"detail": "Template engine is not configured", "extra": None, "status_code": 500} - - -def test_template_with_no_context(tmpdir: Any) -> None: - path = os.path.join(tmpdir, "index.html") - with open(path, "w") as file: - file.write("<html>This works!</html>") - - @get(path="/") - def index() -> Template: - return Template(name="index.html") - - with create_test_client( - route_handlers=[index], - template_config=TemplateConfig(engine=JinjaTemplateEngine, directory=tmpdir), - ) as client: - index_response = client.request("GET", "/") - assert index_response.status_code == 200 - assert index_response.text == "<html>This works!</html>" - assert index_response.headers["Content-Type"] == "text/html; charset=utf-8"
template additional config How can this be achieved with the current way the template config is used? ```python templates = Jinja2Templates(directory="templates") templates.env.globals[’flashed_messages’] = flashed_messages ```
I cannot see an obvious way, nor any mention of setting globals in the docs, so hopefully I haven't missed anything. The jinja `Environment` is constructed in `starlite.template.jinja.JinjaTemplateEngine`: ```python class JinjaTemplateEngine(TemplateEngineProtocol[JinjaTemplate]): """Template engine using the jinja templating library""" def __init__(self, directory: Union[DirectoryPath, List[DirectoryPath]]) -> None: super().__init__(directory) loader = FileSystemLoader(searchpath=directory) self.engine = Environment(loader=loader, autoescape=True) ``` According to [jinja docs](https://jinja.palletsprojects.com/en/3.1.x/api/#jinja2.Environment.globals) that `Environment` object has a `globals` attribute which is a dict for storing those variables in. So maybe we could do something like: ```python templates = TemplateConfig( directory="templates", engine=JinjaTemplateEngine, globals={"flashed_messages": flashed_messages} ) ``` @peterschutt are you saying that you can implement into the code base or it should already work? I have tried that but errors with `UndefinedError: 'flashed_messages' is undefined` when trying to call it in the template. That is a suggestion of a potential api design to solve the problem you have, it would need to be implemented. +1, We can also expose and propagate `**kwargs`
2022-06-24T13:21:21
litestar-org/litestar
174
litestar-org__litestar-174
[ "130" ]
a94eed8885f6de4f52b2ee876e9f932cd72e280d
diff --git a/starlite/__init__.py b/starlite/__init__.py --- a/starlite/__init__.py +++ b/starlite/__init__.py @@ -1,3 +1,5 @@ +from typing import TYPE_CHECKING, Any + from starlite.datastructures import File, Redirect, State, Stream, Template from .app import Starlite @@ -53,9 +55,12 @@ from .response import Response from .router import Router from .routes import BaseRoute, HTTPRoute, WebSocketRoute -from .testing import TestClient, create_test_client, create_test_request from .types import MiddlewareProtocol, Partial, ResponseHeader +if TYPE_CHECKING: + from .testing import TestClient, create_test_client, create_test_request + + __all__ = [ "ASGIRouteHandler", "AbstractAuthenticationMiddleware", @@ -121,3 +126,17 @@ "route", "websocket", ] + +_dynamic_imports = {"TestClient", "create_test_client", "create_test_request"} + + +# pylint: disable=import-outside-toplevel +def __getattr__(name: str) -> Any: + """Provide lazy importing as per https://peps.python.org/pep-0562/""" + if name not in _dynamic_imports: + raise AttributeError(f"Module {__package__} has no attribute {name}") + + from . import testing + + attr = globals()[name] = getattr(testing, name) + return attr
diff --git a/starlite/testing.py b/starlite/testing.py --- a/starlite/testing.py +++ b/starlite/testing.py @@ -4,7 +4,15 @@ from orjson import dumps from pydantic import BaseModel from pydantic.typing import AnyCallable -from requests.models import RequestEncodingMixin + +try: + from requests.models import RequestEncodingMixin +except ImportError: # pragma: no cover + from starlite.exceptions import MissingDependencyException + + raise MissingDependencyException( + "To use starlite.testing, intall starlite with 'testing' extra, e.g. `pip install starlite[testing]`" + ) from starlette.middleware import Middleware from starlette.middleware.base import BaseHTTPMiddleware from starlette.testclient import TestClient as StarletteTestClient @@ -35,6 +43,12 @@ MiddlewareProtocol, ) +__all__ = [ + "TestClient", + "create_test_client", + "create_test_request", +] + class RequestEncoder(RequestEncodingMixin): def multipart_encode(self, data: Dict[str, Any]) -> Tuple[bytes, str]: diff --git a/tests/test_imports.py b/tests/test_imports.py new file mode 100644 --- /dev/null +++ b/tests/test_imports.py @@ -0,0 +1,41 @@ +import subprocess +import sys + +import pytest + + [email protected]("starlite" in sys.modules, reason="This tests expects starlite to be imported for the first time") +def test_testing_import_deprecation() -> None: + import starlite + + dynamic_imports_names = {"TestClient", "create_test_client", "create_test_request"} + assert dynamic_imports_names & starlite.__dict__.keys() == set() + assert "starlite.testing" not in sys.modules + assert "requests" not in sys.modules + assert "requests.models" not in sys.modules + + dynamic_imports = {} + for dynamic_import_name in dynamic_imports_names: + dynamic_imports[dynamic_import_name] = getattr(starlite, dynamic_import_name) + + assert dynamic_imports_names & starlite.__dict__.keys() == dynamic_imports_names + assert "starlite.testing" in sys.modules + assert "requests.models" in sys.modules + + from starlite import testing + + assert dynamic_imports == { + "TestClient": testing.TestClient, + "create_test_client": testing.create_test_client, + "create_test_request": testing.create_test_request, + } + + [email protected]( + "starlite" not in sys.modules, reason="Was able to run previous test, no need to launch subprocess for that" +) +def test_testing_import_deprecation_in_subprocess() -> None: + """Run test_testing_import_deprecation in subprocess so it can test importing starlite for the first time""" + subprocess.check_call( + [sys.executable, "-m", "pytest", f"{__file__}::{test_testing_import_deprecation.__name__}"], timeout=5 + )
Move `requests` to `testing` extra I was inspecting starlight dependencies and was confused to see `requests` being required without any obvious reason. I found #13 then, but I disagree with the resolution since I believe libs required for testing purposes should not be installed for normal use. Now it only one lib (with several dependencies), but imagine if more dependencies would be added for testing. #### What I propose: 1. Move requests from required dependencies to `testing` extra (`pip install starlight[testing]`) 1. Remove import of `starlite.testing` from `starlite` package 2. When starlight is imported explicitly (`from starlight import testint`), check for requests installed. if not, raise `RuntimeError("To access starlight.testing install starlight with [testing] extra")` How would `pyproject.toml` of end user look like: ```toml [tool.poetry.dependencies] python = "^3.10" starlite = "^1.3.9" [tool.poetry.dev-dependencies] starlite = {extras = ["testing"], version = "*"} # whatever version is installed + testing dependencies pytest = "^5.2" ``` I can send a PR if changes are welcomed.
Hi @Bobronium. This will be a breaking change because the test client etc. are returned from the bottom level `__init__` at present. @Goldziher, indeed. How big of an issue is that? Is that the only issue you see in the proposal? Well it is. I understand if you want to make it an extra to remove it from the production code - that's fine. But a breaking change is a problem. Is there a way to add it to extra and have it as the default install path? Otherwise I think this is a no go TBH. The other issue is documentation - it needs to be made clear that this is required for the testing component etc. We can overcome this by declaring `__getattr__` in __init__.py ([PEP 562](https://peps.python.org/pep-0562/)) to make smooth transition then: `cat starlight/__init__.py` ```py ... def __getattr__(name: str): if name not in {"TestClient", "create_test_client", "create_test_request"}: raise AttributeError() import warnings warnings.warn(f"Importing {name} from {__package__} is deprecated, use `from startlite.testing import {name}` instead", DeprecationWarning, stacklevel=2) from . import testing attr = globals()[name] = getattr(testing, name) return attr ``` `python -c "from starlite import TestClient; print(TestClient)"` ``` <string>:1: DeprecationWarning: Importing TestClient from starlite is deprecated, use `from startlite.testing impory TestClient` instead <class 'starlite.testing.TestClient'> ``` go ahead and make a PR if it's not a big issue. @peterschutt and myself will check it out - I am apprehensive about breaking code for users TBH, but i am will to test it first. Thanks for contributing! So, should I close this issue? If you don't consider this an issue, sure. I'm still positive on implementing this. Just haven't have time to do it yet. If you're going to implement it, I'll keep it open.
2022-06-25T02:57:14
litestar-org/litestar
183
litestar-org__litestar-183
[ "181" ]
c67e8ffd848841e2bc879aa3bf24e7032a6fad16
diff --git a/starlite/__init__.py b/starlite/__init__.py --- a/starlite/__init__.py +++ b/starlite/__init__.py @@ -1,4 +1,4 @@ -from typing import TYPE_CHECKING, Any +from typing import Any from starlite.datastructures import File, Redirect, State, Stream, Template @@ -57,10 +57,6 @@ from .routes import BaseRoute, HTTPRoute, WebSocketRoute from .types import MiddlewareProtocol, Partial, ResponseHeader -if TYPE_CHECKING: - from .testing import TestClient, create_test_client, create_test_request - - __all__ = [ "ASGIRouteHandler", "AbstractAuthenticationMiddleware", @@ -110,14 +106,11 @@ "Stream", "Template", "TemplateConfig", - "TestClient", "ValidationException", "WebSocket", "WebSocketRoute", "WebsocketRouteHandler", "asgi", - "create_test_client", - "create_test_request", "delete", "get", "patch", @@ -127,15 +120,24 @@ "websocket", ] -_dynamic_imports = {"TestClient", "create_test_client", "create_test_request"} + +_deprecated_imports = {"TestClient", "create_test_client", "create_test_request"} # pylint: disable=import-outside-toplevel def __getattr__(name: str) -> Any: """Provide lazy importing as per https://peps.python.org/pep-0562/""" - if name not in _dynamic_imports: + if name not in _deprecated_imports: raise AttributeError(f"Module {__package__} has no attribute {name}") + import warnings + + warnings.warn( + f"Importing {name} from {__package__} is deprecated, use `from startlite.testing import {name}` instead", + DeprecationWarning, + stacklevel=2, + ) + from . import testing attr = globals()[name] = getattr(testing, name)
diff --git a/tests/app/test_error_handling.py b/tests/app/test_error_handling.py --- a/tests/app/test_error_handling.py +++ b/tests/app/test_error_handling.py @@ -3,18 +3,9 @@ from starlette.exceptions import HTTPException as StarletteHTTPException from starlette.status import HTTP_400_BAD_REQUEST, HTTP_500_INTERNAL_SERVER_ERROR -from starlite import ( - HTTPException, - MediaType, - Request, - Response, - Starlite, - TestClient, - create_test_client, - get, - post, -) +from starlite import HTTPException, MediaType, Request, Response, Starlite, get, post from starlite.exceptions import InternalServerException +from starlite.testing import TestClient, create_test_client from tests import Person diff --git a/tests/app/test_lifecycle.py b/tests/app/test_lifecycle.py --- a/tests/app/test_lifecycle.py +++ b/tests/app/test_lifecycle.py @@ -1,6 +1,7 @@ from typing import cast -from starlite import Starlite, State, create_test_client +from starlite import Starlite, State +from starlite.testing import create_test_client def test_lifecycle() -> None: diff --git a/tests/app/test_middleware_handling.py b/tests/app/test_middleware_handling.py --- a/tests/app/test_middleware_handling.py +++ b/tests/app/test_middleware_handling.py @@ -17,10 +17,10 @@ Request, Response, Starlite, - create_test_client, get, post, ) +from starlite.testing import create_test_client logger = logging.getLogger(__name__) diff --git a/tests/dependency_injection/test_http_handler_dependency_injection.py b/tests/dependency_injection/test_http_handler_dependency_injection.py --- a/tests/dependency_injection/test_http_handler_dependency_injection.py +++ b/tests/dependency_injection/test_http_handler_dependency_injection.py @@ -3,8 +3,9 @@ from starlette.status import HTTP_200_OK, HTTP_400_BAD_REQUEST -from starlite import Controller, Provide, create_test_client, get +from starlite import Controller, Provide, get from starlite.connection import Request +from starlite.testing import create_test_client def router_first_dependency() -> bool: diff --git a/tests/dependency_injection/test_injection_of_generic_models.py b/tests/dependency_injection/test_injection_of_generic_models.py --- a/tests/dependency_injection/test_injection_of_generic_models.py +++ b/tests/dependency_injection/test_injection_of_generic_models.py @@ -4,7 +4,8 @@ from pydantic.generics import GenericModel from starlette.status import HTTP_200_OK -from starlite import Provide, create_test_client, get +from starlite import Provide, get +from starlite.testing import create_test_client T = TypeVar("T") diff --git a/tests/dependency_injection/test_inter_dependencies.py b/tests/dependency_injection/test_inter_dependencies.py --- a/tests/dependency_injection/test_inter_dependencies.py +++ b/tests/dependency_injection/test_inter_dependencies.py @@ -1,4 +1,5 @@ -from starlite import Controller, MediaType, Provide, create_test_client, get +from starlite import Controller, MediaType, Provide, get +from starlite.testing import create_test_client def test_inter_dependencies() -> None: diff --git a/tests/dependency_injection/test_websocket_handler_dependency_injection.py b/tests/dependency_injection/test_websocket_handler_dependency_injection.py --- a/tests/dependency_injection/test_websocket_handler_dependency_injection.py +++ b/tests/dependency_injection/test_websocket_handler_dependency_injection.py @@ -4,8 +4,9 @@ import pytest from starlette.websockets import WebSocketDisconnect -from starlite import Controller, Provide, create_test_client, websocket +from starlite import Controller, Provide, websocket from starlite.connection import WebSocket +from starlite.testing import create_test_client def router_first_dependency() -> bool: diff --git a/tests/handlers/asgi/test_handle_asgi.py b/tests/handlers/asgi/test_handle_asgi.py --- a/tests/handlers/asgi/test_handle_asgi.py +++ b/tests/handlers/asgi/test_handle_asgi.py @@ -1,7 +1,8 @@ from starlette.status import HTTP_200_OK from starlette.types import Receive, Scope, Send -from starlite import Controller, MediaType, Response, asgi, create_test_client +from starlite import Controller, MediaType, Response, asgi +from starlite.testing import create_test_client def test_handle_asgi() -> None: diff --git a/tests/handlers/asgi/test_validations.py b/tests/handlers/asgi/test_validations.py --- a/tests/handlers/asgi/test_validations.py +++ b/tests/handlers/asgi/test_validations.py @@ -1,7 +1,8 @@ import pytest from starlette.types import Receive, Scope, Send -from starlite import ImproperlyConfiguredException, asgi, create_test_client +from starlite import ImproperlyConfiguredException, asgi +from starlite.testing import create_test_client def test_asgi_handler_validation() -> None: diff --git a/tests/handlers/http/test_sync.py b/tests/handlers/http/test_sync.py --- a/tests/handlers/http/test_sync.py +++ b/tests/handlers/http/test_sync.py @@ -1,6 +1,7 @@ import pytest -from starlite import HTTPRouteHandler, MediaType, create_test_client, get +from starlite import HTTPRouteHandler, MediaType, get +from starlite.testing import create_test_client def sync_handler() -> str: diff --git a/tests/handlers/websocket/test_handle_websocket.py b/tests/handlers/websocket/test_handle_websocket.py --- a/tests/handlers/websocket/test_handle_websocket.py +++ b/tests/handlers/websocket/test_handle_websocket.py @@ -1,4 +1,5 @@ -from starlite import WebSocket, create_test_client, websocket +from starlite import WebSocket, websocket +from starlite.testing import create_test_client def test_handle_websocket() -> None: diff --git a/tests/handlers/websocket/test_kwarg_handling.py b/tests/handlers/websocket/test_kwarg_handling.py --- a/tests/handlers/websocket/test_kwarg_handling.py +++ b/tests/handlers/websocket/test_kwarg_handling.py @@ -1,4 +1,5 @@ -from starlite import Parameter, WebSocket, create_test_client, websocket +from starlite import Parameter, WebSocket, websocket +from starlite.testing import create_test_client def test_handle_websocket_params_parsing() -> None: diff --git a/tests/handlers/websocket/test_validations.py b/tests/handlers/websocket/test_validations.py --- a/tests/handlers/websocket/test_validations.py +++ b/tests/handlers/websocket/test_validations.py @@ -2,12 +2,8 @@ import pytest -from starlite import ( - ImproperlyConfiguredException, - WebSocket, - create_test_client, - websocket, -) +from starlite import ImproperlyConfiguredException, WebSocket, websocket +from starlite.testing import create_test_client def test_websocket_handler_function_validation() -> None: diff --git a/tests/kwargs/test_cookie_params.py b/tests/kwargs/test_cookie_params.py --- a/tests/kwargs/test_cookie_params.py +++ b/tests/kwargs/test_cookie_params.py @@ -5,7 +5,8 @@ from starlette.status import HTTP_200_OK, HTTP_400_BAD_REQUEST from typing_extensions import Type -from starlite import Parameter, create_test_client, get +from starlite import Parameter, get +from starlite.testing import create_test_client @pytest.mark.parametrize( diff --git a/tests/kwargs/test_defaults.py b/tests/kwargs/test_defaults.py --- a/tests/kwargs/test_defaults.py +++ b/tests/kwargs/test_defaults.py @@ -1,6 +1,7 @@ from starlette.status import HTTP_200_OK -from starlite import Parameter, create_test_client, get +from starlite import Parameter, get +from starlite.testing import create_test_client def test_params_default() -> None: diff --git a/tests/kwargs/test_header_params.py b/tests/kwargs/test_header_params.py --- a/tests/kwargs/test_header_params.py +++ b/tests/kwargs/test_header_params.py @@ -7,7 +7,8 @@ from starlette.status import HTTP_200_OK, HTTP_400_BAD_REQUEST from typing_extensions import Type -from starlite import Parameter, create_test_client, get +from starlite import Parameter, get +from starlite.testing import create_test_client @pytest.mark.parametrize( diff --git a/tests/kwargs/test_json_data.py b/tests/kwargs/test_json_data.py --- a/tests/kwargs/test_json_data.py +++ b/tests/kwargs/test_json_data.py @@ -1,6 +1,7 @@ from starlette.status import HTTP_201_CREATED -from starlite import Body, RequestEncodingType, create_test_client, post +from starlite import Body, RequestEncodingType, post +from starlite.testing import create_test_client from tests.kwargs import Form diff --git a/tests/kwargs/test_multipart_data.py b/tests/kwargs/test_multipart_data.py --- a/tests/kwargs/test_multipart_data.py +++ b/tests/kwargs/test_multipart_data.py @@ -5,7 +5,8 @@ from starlette.datastructures import UploadFile from starlette.status import HTTP_201_CREATED -from starlite import Body, RequestEncodingType, create_test_client, post +from starlite import Body, RequestEncodingType, post +from starlite.testing import create_test_client from tests import Person, PersonFactory from tests.kwargs import Form diff --git a/tests/kwargs/test_path_params.py b/tests/kwargs/test_path_params.py --- a/tests/kwargs/test_path_params.py +++ b/tests/kwargs/test_path_params.py @@ -4,13 +4,8 @@ from pydantic import UUID4 from starlette.status import HTTP_200_OK, HTTP_400_BAD_REQUEST -from starlite import ( - ImproperlyConfiguredException, - Parameter, - Starlite, - create_test_client, - get, -) +from starlite import ImproperlyConfiguredException, Parameter, Starlite, get +from starlite.testing import create_test_client @pytest.mark.parametrize( diff --git a/tests/kwargs/test_query_params.py b/tests/kwargs/test_query_params.py --- a/tests/kwargs/test_query_params.py +++ b/tests/kwargs/test_query_params.py @@ -5,7 +5,8 @@ import pytest from starlette.status import HTTP_200_OK, HTTP_400_BAD_REQUEST -from starlite import Parameter, create_test_client, get +from starlite import Parameter, get +from starlite.testing import create_test_client @pytest.mark.parametrize( diff --git a/tests/kwargs/test_reserved_kwargs_injection.py b/tests/kwargs/test_reserved_kwargs_injection.py --- a/tests/kwargs/test_reserved_kwargs_injection.py +++ b/tests/kwargs/test_reserved_kwargs_injection.py @@ -12,13 +12,13 @@ Request, Starlite, State, - create_test_client, delete, get, patch, post, put, ) +from starlite.testing import create_test_client from tests import Person, PersonFactory diff --git a/tests/kwargs/test_url_encoded_data.py b/tests/kwargs/test_url_encoded_data.py --- a/tests/kwargs/test_url_encoded_data.py +++ b/tests/kwargs/test_url_encoded_data.py @@ -1,6 +1,7 @@ from starlette.status import HTTP_201_CREATED -from starlite import Body, RequestEncodingType, create_test_client, post +from starlite import Body, RequestEncodingType, post +from starlite.testing import create_test_client from tests.kwargs import Form diff --git a/tests/middleware/test_authentication.py b/tests/middleware/test_authentication.py --- a/tests/middleware/test_authentication.py +++ b/tests/middleware/test_authentication.py @@ -10,10 +10,11 @@ ) from starlette.websockets import WebSocketDisconnect -from starlite import Starlite, create_test_client, get, websocket +from starlite import Starlite, get, websocket from starlite.connection import Request, WebSocket from starlite.exceptions import PermissionDeniedException from starlite.middleware import AbstractAuthenticationMiddleware, AuthenticationResult +from starlite.testing import create_test_client class User(BaseModel): diff --git a/tests/openapi/test_integration.py b/tests/openapi/test_integration.py --- a/tests/openapi/test_integration.py +++ b/tests/openapi/test_integration.py @@ -5,9 +5,10 @@ from orjson import loads from starlette.status import HTTP_200_OK -from starlite import Starlite, create_test_client +from starlite import Starlite from starlite.app import DEFAULT_OPENAPI_CONFIG from starlite.enums import OpenAPIMediaType +from starlite.testing import create_test_client from tests.openapi.utils import PersonController, PetController diff --git a/tests/openapi/test_schema.py b/tests/openapi/test_schema.py --- a/tests/openapi/test_schema.py +++ b/tests/openapi/test_schema.py @@ -5,15 +5,7 @@ from openapi_schema_pydantic.v3.v3_1_0.schema import Schema from pydantic.fields import FieldInfo -from starlite import ( - Controller, - MediaType, - Parameter, - Provide, - Starlite, - create_test_client, - get, -) +from starlite import Controller, MediaType, Parameter, Provide, Starlite, get from starlite.app import DEFAULT_OPENAPI_CONFIG from starlite.exceptions import ImproperlyConfiguredException from starlite.openapi.constants import ( @@ -21,6 +13,7 @@ PYDANTIC_TO_OPENAPI_PROPERTY_MAP, ) from starlite.openapi.schema import update_schema_with_field_info +from starlite.testing import create_test_client def test_update_schema_with_field_info() -> None: diff --git a/tests/plugins/sql_alchemy_plugin/test_sql_alchemy_plugin_integration.py b/tests/plugins/sql_alchemy_plugin/test_sql_alchemy_plugin_integration.py --- a/tests/plugins/sql_alchemy_plugin/test_sql_alchemy_plugin_integration.py +++ b/tests/plugins/sql_alchemy_plugin/test_sql_alchemy_plugin_integration.py @@ -6,8 +6,9 @@ ) from starlette.status import HTTP_200_OK, HTTP_201_CREATED -from starlite import create_test_client, get, post +from starlite import get, post from starlite.plugins.sql_alchemy import SQLAlchemyPlugin +from starlite.testing import create_test_client from tests.plugins.sql_alchemy_plugin import Company companies = [ diff --git a/tests/request/test_state.py b/tests/request/test_state.py --- a/tests/request/test_state.py +++ b/tests/request/test_state.py @@ -2,7 +2,8 @@ from starlette.types import ASGIApp, Receive, Scope, Send -from starlite import MiddlewareProtocol, Request, create_test_client, get +from starlite import MiddlewareProtocol, Request, get +from starlite.testing import create_test_client class BeforeRequestMiddleWare(MiddlewareProtocol): diff --git a/tests/static_files/test_static_files.py b/tests/static_files/test_static_files.py --- a/tests/static_files/test_static_files.py +++ b/tests/static_files/test_static_files.py @@ -3,8 +3,8 @@ import pytest from pydantic import ValidationError -from starlite import create_test_client from starlite.config import StaticFilesConfig +from starlite.testing import create_test_client def test_staticfiles(tmpdir: Any) -> None: diff --git a/tests/test_caching.py b/tests/test_caching.py --- a/tests/test_caching.py +++ b/tests/test_caching.py @@ -8,8 +8,9 @@ from freezegun import freeze_time from pydantic import ValidationError -from starlite import CacheConfig, Request, Response, create_test_client, get +from starlite import CacheConfig, Request, Response, get from starlite.cache import SimpleCacheBackend +from starlite.testing import create_test_client async def slow_handler() -> dict: diff --git a/tests/test_connection_lifecycle_hooks.py b/tests/test_connection_lifecycle_hooks.py --- a/tests/test_connection_lifecycle_hooks.py +++ b/tests/test_connection_lifecycle_hooks.py @@ -2,15 +2,8 @@ import pytest -from starlite import ( - Controller, - HTTPRouteHandler, - Request, - Response, - Router, - create_test_client, - get, -) +from starlite import Controller, HTTPRouteHandler, Request, Response, Router, get +from starlite.testing import create_test_client from starlite.types import AfterRequestHandler, BeforeRequestHandler diff --git a/tests/test_controller.py b/tests/test_controller.py --- a/tests/test_controller.py +++ b/tests/test_controller.py @@ -6,7 +6,6 @@ Controller, HttpMethod, HTTPRouteHandler, - create_test_client, delete, get, patch, @@ -15,6 +14,7 @@ websocket, ) from starlite.connection import WebSocket +from starlite.testing import create_test_client from tests import Person, PersonFactory diff --git a/tests/test_dto_factory.py b/tests/test_dto_factory.py --- a/tests/test_dto_factory.py +++ b/tests/test_dto_factory.py @@ -6,15 +6,9 @@ from pydantic_factories import ModelFactory from starlette.status import HTTP_200_OK, HTTP_201_CREATED -from starlite import ( - DTOFactory, - ImproperlyConfiguredException, - Starlite, - create_test_client, - get, - post, -) +from starlite import DTOFactory, ImproperlyConfiguredException, Starlite, get, post from starlite.plugins.sql_alchemy import SQLAlchemyPlugin +from starlite.testing import create_test_client from tests import Person from tests import Pet as PydanticPet from tests import Species, VanillaDataClassPerson diff --git a/tests/test_exception_handlers.py b/tests/test_exception_handlers.py --- a/tests/test_exception_handlers.py +++ b/tests/test_exception_handlers.py @@ -13,9 +13,9 @@ Router, ServiceUnavailableException, ValidationException, - create_test_client, get, ) +from starlite.testing import create_test_client from starlite.types import ExceptionHandler diff --git a/tests/test_guards.py b/tests/test_guards.py --- a/tests/test_guards.py +++ b/tests/test_guards.py @@ -10,12 +10,12 @@ Request, Response, asgi, - create_test_client, get, websocket, ) from starlite.connection import WebSocket from starlite.exceptions import PermissionDeniedException +from starlite.testing import create_test_client async def local_guard(_: HTTPConnection, route_handler: BaseRouteHandler) -> None: diff --git a/tests/test_imports.py b/tests/test_imports.py --- a/tests/test_imports.py +++ b/tests/test_imports.py @@ -1,30 +1,39 @@ import subprocess import sys +import warnings import pytest +deprecated_imports_names = {"TestClient", "create_test_client", "create_test_request"} + @pytest.mark.skipif("starlite" in sys.modules, reason="This tests expects starlite to be imported for the first time") def test_testing_import_deprecation() -> None: import starlite - dynamic_imports_names = {"TestClient", "create_test_client", "create_test_request"} - assert dynamic_imports_names & starlite.__dict__.keys() == set() + assert deprecated_imports_names & starlite.__dict__.keys() == set() assert "starlite.testing" not in sys.modules assert "requests" not in sys.modules assert "requests.models" not in sys.modules - dynamic_imports = {} - for dynamic_import_name in dynamic_imports_names: - dynamic_imports[dynamic_import_name] = getattr(starlite, dynamic_import_name) + imported_values = {} + for dynamic_import_name in deprecated_imports_names: + with pytest.warns(DeprecationWarning): + imported_values[dynamic_import_name] = getattr(starlite, dynamic_import_name) - assert dynamic_imports_names & starlite.__dict__.keys() == dynamic_imports_names + assert deprecated_imports_names & starlite.__dict__.keys() == deprecated_imports_names assert "starlite.testing" in sys.modules assert "requests.models" in sys.modules + # ensure no warnings emitted on the second usage + with warnings.catch_warnings(record=True) as record: + for deprecated_name in deprecated_imports_names: + getattr(starlite, deprecated_name) + + assert record == [] from starlite import testing - assert dynamic_imports == { + assert imported_values == { "TestClient": testing.TestClient, "create_test_client": testing.create_test_client, "create_test_request": testing.create_test_request, @@ -39,3 +48,9 @@ def test_testing_import_deprecation_in_subprocess() -> None: subprocess.check_call( [sys.executable, "-m", "pytest", f"{__file__}::{test_testing_import_deprecation.__name__}"], timeout=5 ) + + +def test_star_import_doesnt_import_testing() -> None: + import starlite + + assert set(starlite.__all__) & deprecated_imports_names == set() diff --git a/tests/test_logging.py b/tests/test_logging.py --- a/tests/test_logging.py +++ b/tests/test_logging.py @@ -3,8 +3,9 @@ from _pytest.logging import LogCaptureFixture -from starlite import Starlite, TestClient, create_test_client +from starlite import Starlite from starlite.logging import LoggingConfig +from starlite.testing import TestClient, create_test_client @patch("logging.config.dictConfig") diff --git a/tests/test_parsers.py b/tests/test_parsers.py --- a/tests/test_parsers.py +++ b/tests/test_parsers.py @@ -1,5 +1,5 @@ -from starlite import create_test_request from starlite.parsers import parse_query_params +from starlite.testing import create_test_request def test_parse_query_params() -> None: diff --git a/tests/test_path_resolution.py b/tests/test_path_resolution.py --- a/tests/test_path_resolution.py +++ b/tests/test_path_resolution.py @@ -10,14 +10,8 @@ ) from typing_extensions import Type -from starlite import ( - Controller, - HTTPRouteHandler, - MediaType, - create_test_client, - delete, - get, -) +from starlite import Controller, HTTPRouteHandler, MediaType, delete, get +from starlite.testing import create_test_client from tests import Person, PersonFactory diff --git a/tests/test_template.py b/tests/test_template.py --- a/tests/test_template.py +++ b/tests/test_template.py @@ -1,9 +1,10 @@ import os from typing import Any -from starlite import Template, TemplateConfig, create_test_client, get +from starlite import Template, TemplateConfig, get from starlite.template.jinja import JinjaTemplateEngine from starlite.template.mako import MakoTemplateEngine +from starlite.testing import create_test_client def test_jinja_template(tmpdir: Any) -> None: diff --git a/tests/test_testing.py b/tests/test_testing.py --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -3,15 +3,8 @@ from hypothesis import HealthCheck, given, settings from hypothesis import strategies as st -from starlite import ( - HttpMethod, - RequestEncodingType, - Starlite, - State, - TestClient, - create_test_request, - get, -) +from starlite import HttpMethod, RequestEncodingType, Starlite, State, get +from starlite.testing import TestClient, create_test_request from tests import Person
`from starlite import *` broken if `testing` extra not installed This is only an issue on main, not in any release. When I want to try a library out, I'll install it into a fresh env, run python repl and do `from lib import *` and have a play around. If just doing that raised an error it would freak me out a little about the lib. Possible solution: - remove `.testing` imports from `starlite.__all__` - add deprecation warning for top-level `.testing` imports - remove `if TYPE_CHECKING` too? May as well if we are doing the above, I think? Refs: #174 #130
2022-06-27T01:55:20
litestar-org/litestar
186
litestar-org__litestar-186
[ "176" ]
2f002e1931557df73f2557ea03fe2fc381ad6ae4
diff --git a/starlite/utils/exception.py b/starlite/utils/exception.py --- a/starlite/utils/exception.py +++ b/starlite/utils/exception.py @@ -1,5 +1,5 @@ from inspect import getmro -from typing import Dict, Optional, Type, Union, cast +from typing import Dict, Optional, Type, Union from starlette.exceptions import HTTPException from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR @@ -13,16 +13,33 @@ def get_exception_handler( """ Given a dictionary that maps exceptions and status codes to handler functions, and an exception, returns the appropriate handler if existing. + + Status codes are given preference over exception type. + + If no status code match exists, each class in the MRO of the exception type is checked and + the first matching handler is returned. + + Finally, if a `500` handler is registered, it will be returned for any exception that isn't a + subclass of `HTTPException`. + + Parameters + ---------- + exception_handlers : dict[int | type[Exception], ExceptionHandler] + Mapping of status codes and exception types to handlers. + exc : Exception + Instance to be resolved to a handler. + + Returns + ------- + Exception | None """ if not exception_handlers: return None if isinstance(exc, HTTPException) and exc.status_code in exception_handlers: return exception_handlers[exc.status_code] - if type(exc) in exception_handlers: - return exception_handlers[type(exc)] - if HTTP_500_INTERNAL_SERVER_ERROR in exception_handlers: - return exception_handlers[HTTP_500_INTERNAL_SERVER_ERROR] for cls in getmro(type(exc)): if cls in exception_handlers: - return exception_handlers[cast(Type[Exception], cls)] + return exception_handlers[cls] + if not isinstance(exc, HTTPException) and HTTP_500_INTERNAL_SERVER_ERROR in exception_handlers: + return exception_handlers[HTTP_500_INTERNAL_SERVER_ERROR] return None
diff --git a/tests/utils/test_exceptions.py b/tests/utils/test_exceptions.py --- a/tests/utils/test_exceptions.py +++ b/tests/utils/test_exceptions.py @@ -3,7 +3,7 @@ import pytest from starlette.status import HTTP_400_BAD_REQUEST, HTTP_500_INTERNAL_SERVER_ERROR -from starlite import InternalServerException, ValidationException +from starlite import HTTPException, InternalServerException, ValidationException from starlite.types import ExceptionHandler from starlite.utils.exception import get_exception_handler @@ -12,6 +12,10 @@ def handler(_: Any, __: Any) -> Any: return None +def handler_2(_: Any, __: Any) -> Any: + return None + + @pytest.mark.parametrize( ["mapping", "exc", "expected"], [ @@ -23,6 +27,11 @@ def handler(_: Any, __: Any) -> Any: ({Exception: handler}, ValidationException(), handler), ({ValueError: handler}, ValidationException(), handler), ({ValidationException: handler}, Exception(), None), + ({HTTP_500_INTERNAL_SERVER_ERROR: handler}, ValidationException(), None), + ({HTTP_500_INTERNAL_SERVER_ERROR: handler, HTTPException: handler_2}, ValidationException(), handler_2), + ({HTTPException: handler, ValidationException: handler_2}, ValidationException(), handler_2), + ({HTTPException: handler, ValidationException: handler_2}, InternalServerException(), handler), + ({HTTP_500_INTERNAL_SERVER_ERROR: handler, HTTPException: handler_2}, InternalServerException(), handler), ], ) def test_get_exception_handler(
`get_exception_handler()` util resolve ordering. https://github.com/starlite-api/starlite/blob/da79c068c906740a4375d431953f1c74fdea8067/starlite/utils/exception.py#L10-L28 I've registered an exception handler to `500_INTERNAL_SERVER_ERROR` that logs the exception but it is also catching and logging `HTTPException` instances. Even if I register an exception handler to `HTTPException` to try to avoid that, because I also have a handler registered for `500` that conditional is always hit and the handler returned before it has the chance to do the walk MRO thing. So I think the mro walk should be above the `500` fallback, and then I think we should think of whether we'd actually want the `HTTPException` subclasses to be pulled in with the `500` handler if there isn't a narrower mapping. This is the registration mapping: ```python exception_handlers={ HTTP_500_INTERNAL_SERVER_ERROR: logging_exception_handler, HTTPException: passthrough_exception_handler, # type:ignore[dict-item] }, ``` But `HTTPException` sub-classes are getting sucked up by this: ```python if HTTP_500_INTERNAL_SERVER_ERROR in exception_handlers: return exception_handlers[HTTP_500_INTERNAL_SERVER_ERROR] ``` ... before the mro check can find the base class mapping.
By the way, to work around it is easy enough, just to register the logging handler to `Exception` instead of the `500`, so not massively urgent to fix. ```python exception_handlers={ Exception: logging_exception_handler, InternalServerException: logging_exception_handler, HTTPException: passthrough_exception_handler, }, ``` Aight, let's update the ordering
2022-06-27T08:48:47
litestar-org/litestar
202
litestar-org__litestar-202
[ "194" ]
b5e934a8c34f3edde7b3adce8a4c7f101a7b7fbc
diff --git a/starlite/signature.py b/starlite/signature.py --- a/starlite/signature.py +++ b/starlite/signature.py @@ -22,7 +22,11 @@ from typing_extensions import get_args from starlite.connection import Request, WebSocket -from starlite.exceptions import ImproperlyConfiguredException, ValidationException +from starlite.exceptions import ( + ImproperlyConfiguredException, + InternalServerException, + ValidationException, +) from starlite.plugins.base import PluginMapping, PluginProtocol, get_plugin_for_value from starlite.utils.dependency import is_dependency_field from starlite.utils.typing import detect_optional_union @@ -37,6 +41,7 @@ class Config(BaseConfig): field_plugin_mappings: ClassVar[Dict[str, PluginMapping]] return_annotation: ClassVar[Any] has_kwargs: ClassVar[bool] + # this is the factory instance used to construct the model factory: ClassVar["SignatureModelFactory"] @classmethod @@ -50,8 +55,8 @@ def parse_values_from_connection_kwargs( This is not equivalent to calling the '.dict' method of the pydantic model, because it doesn't convert nested values into dictionary, just extracts the data from the signature model """ + output: Dict[str, Any] = {} try: - output: Dict[str, Any] = {} modelled_signature = cls(**kwargs) for key in cls.__fields__: value = modelled_signature.__getattribute__(key) # pylint: disable=unnecessary-dunder-call @@ -70,12 +75,47 @@ def parse_values_from_connection_kwargs( ) else: output[key] = value - return output except ValidationError as e: - raise ValidationException( - detail=f"Validation failed for {connection.method if isinstance(connection, Request) else 'websocket'} {connection.url}", - extra=e.errors(), - ) from e + raise cls.construct_exception(connection, e) from e + return output + + @classmethod + def construct_exception( + cls, connection: Union[Request, WebSocket], exc: ValidationError + ) -> Union[InternalServerException, ValidationException]: + """ + Distinguish between validation errors that arise from parameters and dependencies. + + If both parameter and dependency values are invalid, we raise the client error first. + + Parameters + ---------- + connection : Request | WebSocket + exc : ValidationError + + Returns + ------- + ValidationException | InternalServerException + """ + client_errors = [] + server_errors = [] + for error in exc.errors(): + if error["loc"][-1] in cls.factory.dependency_name_set: + server_errors.append(error) + else: + client_errors.append(error) + method = connection.method if isinstance(connection, Request) else "websocket" + + if client_errors: + return ValidationException( + detail=f"Validation failed for {method} {connection.url}", + extra=client_errors, + ) + + return InternalServerException( + detail=f"A dependency failed validation for {method} {connection.url}", + extra=server_errors, + ) @dataclass
diff --git a/tests/test_signature.py b/tests/test_signature.py --- a/tests/test_signature.py +++ b/tests/test_signature.py @@ -4,8 +4,10 @@ import pytest from starlette.status import HTTP_204_NO_CONTENT -from starlite import ImproperlyConfiguredException, get +from starlite import ImproperlyConfiguredException, Provide, get +from starlite.params import Dependency from starlite.signature import SignatureModelFactory +from starlite.testing import create_test_client def test_create_function_signature_model_parameter_parsing() -> None: @@ -50,3 +52,57 @@ async def health_check() -> None: def test_create_function_signature_model_validation() -> None: with pytest.raises(ImproperlyConfiguredException): SignatureModelFactory(lru_cache(maxsize=0)(lambda x: x), [], set()).model().dict() # type: ignore + + +def test_dependency_validation_failure_raises_500() -> None: + + dependencies = {"dep": Provide(lambda: "thirteen")} + + @get("/") + def test(dep: int, param: int, optional_dep: Optional[int] = Dependency()) -> None: + ... + + with create_test_client(route_handlers=[test], dependencies=dependencies) as client: + resp = client.get("/?param=13") + + assert resp.json() == { + "detail": "A dependency failed validation for GET http://testserver/?param=13", + "extra": [{"loc": ["dep"], "msg": "value is not a valid integer", "type": "type_error.integer"}], + "status_code": 500, + } + + +def test_validation_failure_raises_400() -> None: + + dependencies = {"dep": Provide(lambda: 13)} + + @get("/") + def test(dep: int, param: int, optional_dep: Optional[int] = Dependency()) -> None: + ... + + with create_test_client(route_handlers=[test], dependencies=dependencies) as client: + resp = client.get("/?param=thirteen") + + assert resp.json() == { + "detail": "Validation failed for GET http://testserver/?param=thirteen", + "extra": [{"loc": ["param"], "msg": "value is not a valid integer", "type": "type_error.integer"}], + "status_code": 400, + } + + +def test_client_error_precedence_over_server_error() -> None: + + dependencies = {"dep": Provide(lambda: "thirteen"), "optional_dep": Provide(lambda: "thirty-one")} + + @get("/") + def test(dep: int, param: int, optional_dep: Optional[int] = Dependency()) -> None: + ... + + with create_test_client(route_handlers=[test], dependencies=dependencies) as client: + resp = client.get("/?param=thirteen") + + assert resp.json() == { + "detail": "Validation failed for GET http://testserver/?param=thirteen", + "extra": [{"loc": ["param"], "msg": "value is not a valid integer", "type": "type_error.integer"}], + "status_code": 400, + }
Bug: status for dependency validation should be changed to 500. Originally from #138 When a value returned from a provided dependency fails pydantic validation, user gets a 4xx, but it should really be a 5xx. Ref: https://github.com/starlite-api/starlite/issues/138#issuecomment-1157066885_ <!-- POLAR PLEDGE BADGE START --> --- ## Funding * If you would like to see an issue prioritized, make a pledge towards it! * We receive the pledge once the issue is completed & verified <a href="https://polar.sh/litestar-org/litestar/issues/194"> <picture> <source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/194/pledge.svg?darkmode=1"> <img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/194/pledge.svg"> </picture> </a> <!-- POLAR PLEDGE BADGE END -->
Any advice on process for this one @Goldziher? Basically there is one try/except block that handles this: https://github.com/starlite-api/starlite/blob/main/starlite/signature.py#L56 You can probably add an attribute on the `SignatueModel` that will tell you this info, see the attributes already there - which use a `ClassVar` so pydantic ignores them: https://github.com/starlite-api/starlite/blob/main/starlite/signature.py#L21 Yes OK - so perhaps a set of the names of all function parameters that are known dependencies as a classvar on the sig model and inspect that after the validation error to determine if 4xx or 5xx? Thats how i'd approach it
2022-06-30T14:40:56
litestar-org/litestar
205
litestar-org__litestar-205
[ "204" ]
c7057dc59298eb0bcdc9acc325157a2d0a4addd1
diff --git a/starlite/routes.py b/starlite/routes.py --- a/starlite/routes.py +++ b/starlite/routes.py @@ -89,7 +89,12 @@ def create_handler_kwargs_model(self, route_handler: BaseRouteHandler) -> Kwargs """ dependencies = route_handler.resolve_dependencies() signature_model = get_signature_model(route_handler) - path_parameters = {p["name"] for p in self.path_parameters} + path_parameters = set() + for param in self.path_parameters: + param_name = param["name"] + if param_name in path_parameters: + raise ImproperlyConfiguredException(f"Duplicate parameter '{param_name}' detected in '{self.path}'.") + path_parameters.add(param_name) return KwargsModel.create_for_signature_model( signature_model=signature_model, dependencies=dependencies, path_parameters=path_parameters )
diff --git a/tests/kwargs/test_path_params.py b/tests/kwargs/test_path_params.py --- a/tests/kwargs/test_path_params.py +++ b/tests/kwargs/test_path_params.py @@ -90,3 +90,12 @@ def test_method() -> None: with pytest.raises(ImproperlyConfiguredException): Starlite(route_handlers=[test_method]) + + +def test_duplicate_path_param_validation() -> None: + @get(path="/{param:int}/foo/{param:int}") + def test_method(param: int) -> None: + pass + + with pytest.raises(ImproperlyConfiguredException): + Starlite(route_handlers=[test_method])
Duplicate path parameters should raise exception ~Just beginning to learn the codebase, but excited to contribute something substantial in the future 😄 Currently, routes with duplicate path parameters can be registered to a handler. The conflict is resolved by using the value associated to the last occurrence of the duplicated parameters (see [here](https://github.com/starlite-api/starlite/blob/c7057dc59298eb0bcdc9acc325157a2d0a4addd1/starlite/routes.py#L76-L83)). I would think an exception should be raised when registering the route, or at least that's the behavior I'm used to seeing. The test below currently passes, as a demonstration. ### Current behavior ```python def test_that_currently_passes() -> None: @get(path=["/{some_id:int}/foo/{some_id:int}"], media_type=MediaType.TEXT) def handler_fn(some_id: int) -> str: return str(some_id) with create_test_client(handler_fn) as client: resp = client.get("/1/foo/2") assert resp.status_code == HTTP_200_OK assert resp.text == "2" ``` ### Proposed behavior ```python def test_duplicate_path_param_validation() -> None: @get(path="/{param:int}/foo/{param:int}") def handler_fn(param: int) -> None: pass with pytest.raises(ImproperlyConfiguredException): Starlite(route_handlers=[handler_fn]) ``` ### Possible fix A simple change when creating the kwargs model that checks for repeated params. Currently param names are added to a set without checking for repeats. ```python def create_handler_kwargs_model(self, route_handler: BaseRouteHandler) -> KwargsModel: """ Method to create a KwargsModel for a given route handler """ dependencies = route_handler.resolve_dependencies() signature_model = get_signature_model(route_handler) path_parameters = set() for param in self.path_parameters: param_name = param["name"] if param_name in path_parameters: raise ImproperlyConfiguredException( f"Duplicate path parameters should not be used. Duplicate parameter {{{param_name}}} found in path {self.path}" ) path_parameters.add(param_name) return KwargsModel.create_for_signature_model( signature_model=signature_model, dependencies=dependencies, path_parameters=path_parameters ) ``` <br> Happy to push this, I just still have a very shallow grasp of the codebase so am probably not doing this the best way! <!-- POLAR PLEDGE BADGE START --> --- > [!NOTE] > While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and > [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship. > > Check out all issues funded or available for funding [on our Polar.sh dashboard](https://polar.sh/litestar-org) > * If you would like to see an issue prioritized, make a pledge towards it! > * We receive the pledge once the issue is completed & verified > * This, along with engagement in the community, helps us know which features are a priority to our users. <a href="https://polar.sh/litestar-org/litestar/issues/204"> <picture> <source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/204/pledge.svg?darkmode=1"> <img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/204/pledge.svg"> </picture> </a> <!-- POLAR PLEDGE BADGE END -->
2022-06-30T22:55:50
litestar-org/litestar
262
litestar-org__litestar-262
[ "255" ]
a2c8a86d42fb347133a5c0c278ae9bc950c75cb7
diff --git a/starlite/kwargs.py b/starlite/kwargs.py --- a/starlite/kwargs.py +++ b/starlite/kwargs.py @@ -1,6 +1,17 @@ from typing import Any, Dict, List, NamedTuple, Optional, Set, Tuple, Type, Union, cast -from pydantic.fields import FieldInfo, ModelField, Undefined +from pydantic.fields import ( + SHAPE_DEQUE, + SHAPE_FROZENSET, + SHAPE_LIST, + SHAPE_SEQUENCE, + SHAPE_SET, + SHAPE_TUPLE, + SHAPE_TUPLE_ELLIPSIS, + FieldInfo, + ModelField, + Undefined, +) from starlite.connection import Request, WebSocket from starlite.constants import ( @@ -15,6 +26,17 @@ from starlite.signature import SignatureModel, get_signature_model from starlite.types import ReservedKwargs +# Shapes corresponding to sequences +SEQ_SHAPES = { + SHAPE_LIST, + SHAPE_SET, + SHAPE_SEQUENCE, + SHAPE_TUPLE, + SHAPE_TUPLE_ELLIPSIS, + SHAPE_DEQUE, + SHAPE_FROZENSET, +} + class ParameterDefinition(NamedTuple): param_type: ParamType @@ -22,6 +44,7 @@ class ParameterDefinition(NamedTuple): field_alias: str is_required: bool default_value: Any + is_sequence: bool class Dependency: @@ -65,6 +88,7 @@ class KwargsModel: "expected_path_params", "expected_query_params", "expected_reserved_kwargs", + "sequence_query_parameter_names", ) def __init__( @@ -77,6 +101,7 @@ def __init__( expected_path_params: Set[ParameterDefinition], expected_query_params: Set[ParameterDefinition], expected_reserved_kwargs: Set[ReservedKwargs], + sequence_query_parameter_names: Set[str], ) -> None: self.expected_cookie_params = expected_cookie_params self.expected_dependencies = expected_dependencies @@ -85,6 +110,7 @@ def __init__( self.expected_path_params = expected_path_params self.expected_query_params = expected_query_params self.expected_reserved_kwargs = expected_reserved_kwargs + self.sequence_query_parameter_names = sequence_query_parameter_names self.has_kwargs = ( expected_cookie_params or expected_dependencies @@ -110,10 +136,7 @@ def create_dependency_graph(cls, key: str, dependencies: Dict[str, Provide]) -> @staticmethod def create_parameter_definition( - allow_none: bool, - field_info: FieldInfo, - field_name: str, - path_parameters: Set[str], + allow_none: bool, field_info: FieldInfo, field_name: str, path_parameters: Set[str], is_sequence: bool ) -> ParameterDefinition: """ Creates a ParameterDefition for the given pydantic FieldInfo instance and inserts it into the correct parameter set @@ -141,6 +164,7 @@ def create_parameter_definition( field_alias=field_alias, default_value=default_value, is_required=is_required and (default_value is None and not allow_none), + is_sequence=is_sequence, ) @classmethod @@ -180,6 +204,7 @@ def create_for_signature_model( field_name=field_name, field_info=model_field.field_info, path_parameters=path_parameters, + is_sequence=model_field.shape in SEQ_SHAPES, ) for field_name, model_field in layered_parameters.items() if field_name not in ignored_keys and field_name not in signature_model.__fields__ @@ -190,6 +215,7 @@ def create_for_signature_model( field_name=field_name, field_info=model_field.field_info, path_parameters=path_parameters, + is_sequence=model_field.shape in SEQ_SHAPES, ) for field_name, model_field in signature_model.__fields__.items() if field_name not in ignored_keys and field_name not in layered_parameters @@ -220,6 +246,7 @@ def create_for_signature_model( field_name=field_name, field_info=field_info, path_parameters=path_parameters, + is_sequence=model_field.shape in SEQ_SHAPES, ) ) @@ -227,6 +254,9 @@ def create_for_signature_model( expected_header_parameters = {p for p in param_definitions if p.param_type == ParamType.HEADER} expected_cookie_parameters = {p for p in param_definitions if p.param_type == ParamType.COOKIE} expected_query_parameters = {p for p in param_definitions if p.param_type == ParamType.QUERY} + sequence_query_parameter_names = { + p.field_alias for p in param_definitions if p.param_type == ParamType.QUERY and p.is_sequence + } expected_form_data = None data_model_field = signature_model.__fields__.get("data") @@ -271,6 +301,7 @@ def create_for_signature_model( expected_cookie_params=expected_cookie_parameters, expected_header_params=expected_header_parameters, expected_reserved_kwargs=cast(Set[ReservedKwargs], expected_reserved_kwargs), + sequence_query_parameter_names=sequence_query_parameter_names, ) @classmethod @@ -338,11 +369,19 @@ def validate_raw_kwargs( f"The following kwargs have been used: {', '.join(used_reserved_kwargs)}" ) + def _sequence_or_scalar_param(self, key: str, value: List[str]) -> Union[str, List[str]]: + """ + Returns the first element of 'value' if we expect it to be a scalar value (appears in self.sequence_query_parameter_names) + and it contains only a single element. + """ + return value[0] if key not in self.sequence_query_parameter_names and len(value) == 1 else value + def to_kwargs(self, connection: Union[WebSocket, Request]) -> Dict[str, Any]: """ Return a dictionary of kwargs. Async values, i.e. CoRoutines, are not resolved to ensure this function is sync. """ reserved_kwargs: Dict[str, Any] = {} + connection_query_params = {k: self._sequence_or_scalar_param(k, v) for k, v in connection.query_params.items()} if self.expected_reserved_kwargs: if "state" in self.expected_reserved_kwargs: reserved_kwargs["state"] = connection.app.state.copy() @@ -351,7 +390,7 @@ def to_kwargs(self, connection: Union[WebSocket, Request]) -> Dict[str, Any]: if "cookies" in self.expected_reserved_kwargs: reserved_kwargs["cookies"] = connection.cookies if "query" in self.expected_reserved_kwargs: - reserved_kwargs["query"] = connection.query_params + reserved_kwargs["query"] = connection_query_params if "request" in self.expected_reserved_kwargs: reserved_kwargs["request"] = connection if "socket" in self.expected_reserved_kwargs: @@ -366,9 +405,9 @@ def to_kwargs(self, connection: Union[WebSocket, Request]) -> Dict[str, Any]: for param in self.expected_path_params } query_params = { - param.field_name: connection.query_params[param.field_alias] + param.field_name: connection_query_params[param.field_alias] if param.is_required - else connection.query_params.get(param.field_alias, param.default_value) + else connection_query_params.get(param.field_alias, param.default_value) for param in self.expected_query_params } header_params = { diff --git a/starlite/parsers.py b/starlite/parsers.py --- a/starlite/parsers.py +++ b/starlite/parsers.py @@ -17,9 +17,7 @@ _false_values = {"False", "false"} -def _query_param_reducer( - acc: Dict[str, Union[str, List[str]]], cur: Tuple[str, str] -) -> Dict[str, Union[str, List[str]]]: +def _query_param_reducer(acc: Dict[str, List[str]], cur: Tuple[str, str]) -> Dict[str, List[str]]: """ Reducer function - acc is a dictionary, cur is a tuple of key + value @@ -32,11 +30,9 @@ def _query_param_reducer( value = False # type: ignore param = acc.get(key) if param is None: - acc[key] = value - elif isinstance(param, str): - acc[key] = [param, value] + acc[key] = [value] else: - acc[key].append(value) # type: ignore + acc[key].append(value) return acc
diff --git a/tests/kwargs/test_query_params.py b/tests/kwargs/test_query_params.py --- a/tests/kwargs/test_query_params.py +++ b/tests/kwargs/test_query_params.py @@ -1,5 +1,16 @@ from datetime import datetime -from typing import List, Optional +from typing import ( + Any, + Deque, + Dict, + FrozenSet, + List, + MutableSequence, + Optional, + Set, + Tuple, + Union, +) from urllib.parse import urlencode import pytest @@ -78,6 +89,16 @@ }, False, ), + ( + { + "page": 1, + "pageSize": 1, + "brands": ["Nike"], + "from_date": datetime.now().timestamp(), + "to_date": datetime.now().timestamp(), + }, + False, + ), ], ) def test_query_params(params_dict: dict, should_raise: bool) -> None: @@ -103,3 +124,65 @@ def test_method( assert response.status_code == HTTP_400_BAD_REQUEST else: assert response.status_code == HTTP_200_OK + + [email protected]( + "expected_type,provided_value,default,expected_response_code", + [ + (List[int], [1, 2, 3], ..., HTTP_200_OK), + (List[int], [1], ..., HTTP_200_OK), + (List[str], ["foo", "bar"], Parameter(min_items=1), HTTP_200_OK), + (List[str], ["foo", "bar"], Parameter(min_items=3), HTTP_400_BAD_REQUEST), + (List[int], ["foo", "bar"], ..., HTTP_400_BAD_REQUEST), + (Tuple[int, str, int], (1, "foo", 2), ..., HTTP_200_OK), + (Optional[List[str]], [], None, HTTP_200_OK), + (Any, [1, 2, 3], ..., HTTP_200_OK), + (Union[int, List[int]], [1, 2, 3], None, HTTP_200_OK), + (Union[int, List[int]], [1], None, HTTP_200_OK), + (Deque[int], [1, 2, 3], None, HTTP_200_OK), + (Set[int], [1, 2, 3], None, HTTP_200_OK), + (FrozenSet[int], [1, 2, 3], None, HTTP_200_OK), + (Tuple[int, ...], [1, 2, 3], None, HTTP_200_OK), + (MutableSequence[int], [1, 2, 3], None, HTTP_200_OK), + ], +) +def test_query_param_arrays(expected_type: Any, provided_value: Any, default: Any, expected_response_code: int) -> None: + test_path = "/test" + + @get(test_path) + def test_method_with_default(param: Any = default) -> None: + return None + + @get(test_path) + def test_method_without_default(param: Any) -> None: + return None + + test_method = test_method_without_default if default is ... else test_method_with_default + # Set the type annotation of 'param' in a way mypy can deal with + test_method.fn.__annotations__["param"] = expected_type + + with create_test_client(test_method) as client: + params = urlencode({"param": provided_value}, doseq=True) + response = client.get(f"{test_path}?{params}") + assert response.status_code == expected_response_code + + +def test_query_kwarg() -> None: + test_path = "/test" + + params = urlencode( + { + "a": ["foo", "bar"], + "b": "qux", + }, + doseq=True, + ) + + @get(test_path) + def test_method(a: List[str], b: List[str], query: Dict[str, Union[str, List[str]]]) -> None: + assert query == {"a": ["foo", "bar"], "b": ["qux"]} + return None + + with create_test_client(test_method) as client: + response = client.get(f"{test_path}?{params}") + assert response.status_code == HTTP_200_OK diff --git a/tests/test_parsers.py b/tests/test_parsers.py --- a/tests/test_parsers.py +++ b/tests/test_parsers.py @@ -12,4 +12,10 @@ def test_parse_query_params() -> None: } request = create_test_request(query=query) # type: ignore result = parse_query_params(connection=request) - assert result == query + assert result == { + "value": ["10"], + "veggies": ["tomato", "potato", "aubergine"], + "calories": ["122.53"], + "healthy": [True], + "polluting": [False], + }
Query parameter arrays with 1 element aren't parsed as arrays I've been reading through the docs and so far I'm loving how domain modelling is built in with pydantic! Experimenting with query params I noticed that query parameter arrays with 1 element end up with type `T` rather than `List[T]`. See the example below: ``` from typing import List from starlite import get, Starlite @get("/test") async def test(myArray: List[int]) -> int: return 0 app = Starlite(route_handlers=[test]) ``` Running - `curl "localhost:8000/test?myArray=1"` gives a 400 with `value is not a valid list`. - `curl "localhost:8000/test?myArray=1&myArray=2` is fine. The workaround isn't too bad - declare myArray as `Union[int, List[int]]` and handle the different types in the body of the function, but I wonder if from an ergonomics perspective its nicer to wrap that logic into the library itself? Something like ``` from pydantic.generics import GenericModel from typing import List, Generic, TypeVar DataT = TypeVar('DataT') class QueryParamArray(GenericModel, Generic[DataT]): __root__: Union[DataT, List[DataT]] @property def array(self): return self.__root__ if isinstance(self.__root__, list) else [self.__root__] ``` Then it would be a simple matter of declaring `myArray` as a `QueryParamArray`. Happy to raise a PR to include this but am not sure where the best place to do so is (types.py?). Also happy to be told this is a stupid idea and its up to the users to declare this utility themselves. Thanks in advance
Hi, thanks for reporting. Yes this is a bug. We should infer the type and stick with it. Do you want to submit a PR? We will take care of it otherwise. > Hi, thanks for reporting. > > Yes this is a bug. We should infer the type and stick with it. Do you want to submit a PR? We will take care of it otherwise. Is this open to pick up ? lets let @josepdaniel respond first. If he doesn't respond within the next few hours, go ahead. Also - there wouldn't need to be much adjustment, just a tuning of the parsing logic, which now converts from a list to a single element if the length is one. @Goldziher sure, I'm happy to have a crack at it. I've just started looking at the repo so may take me a few days to get familiar and merge a fix, hope thats alright. > @Goldziher sure, I'm happy to have a crack at it. I've just started looking at the repo so may take me a few days to get familiar and merge a fix, hope thats alright. Take your time
2022-07-07T14:20:52
litestar-org/litestar
288
litestar-org__litestar-288
[ "287" ]
7eb46332a624d28ebefd632189524e9192899cde
diff --git a/starlite/types.py b/starlite/types.py --- a/starlite/types.py +++ b/starlite/types.py @@ -11,6 +11,7 @@ TypeVar, Union, cast, + get_type_hints, ) from openapi_schema_pydantic.v3.v3_1_0.header import Header @@ -23,7 +24,7 @@ from starlette.responses import Response as StarletteResponse from typing_extensions import Literal, Protocol, runtime_checkable -from starlite.exceptions import HTTPException +from starlite.exceptions import HTTPException, ImproperlyConfiguredException from starlite.response import Response try: @@ -103,15 +104,23 @@ def __class_getitem__(cls, item: Type[T]) -> Type[T]: """ Modifies a given T subclass of BaseModel to be all optional """ + if not issubclass(item, BaseModel): + raise ImproperlyConfiguredException(f"Partial[{item}] must be a subclass of BaseModel") if not cls._models.get(item): field_definitions: Dict[str, Tuple[Any, None]] = {} - for field_name, field_type in item.__annotations__.items(): - # we modify the field annotations to make it optional - if not isinstance(field_type, GenericAlias) or type(None) not in field_type.__args__: - field_definitions[field_name] = (Optional[field_type], None) + # traverse the object's mro and get all annotations + # until we find a BaseModel. + for obj in item.mro(): + if issubclass(obj, BaseModel): + for field_name, field_type in get_type_hints(obj).items(): + # we modify the field annotations to make it optional + if not isinstance(field_type, GenericAlias) or type(None) not in field_type.__args__: + field_definitions[field_name] = (Optional[field_type], None) + else: + field_definitions[field_name] = (field_type, None) else: - field_definitions[field_name] = (field_type, None) - cls._models[item] = create_model("Partial" + item.__name__, **field_definitions) # type: ignore + break + cls._models[item] = create_model(f"Partial{item.__name__}", **field_definitions) # type: ignore return cast(Type[T], cls._models.get(item))
diff --git a/tests/test_types.py b/tests/test_types.py --- a/tests/test_types.py +++ b/tests/test_types.py @@ -1,3 +1,9 @@ +from typing import Optional + +from pydantic import BaseModel +from pytest import raises + +from starlite.exceptions import ImproperlyConfiguredException from starlite.types import Partial from tests import Person @@ -16,3 +22,42 @@ def test_partial() -> None: for field in partial.__annotations__.values(): assert isinstance(field, GenericAlias) assert type(None) in field.__args__ + + +def test_partial_superclass() -> None: + """ + Test that Partial returns the correct annotations + for nested models. + """ + + class Parent(BaseModel): + foo: int + + class Child(Parent): + bar: int + + partial_child = Partial[Child] + + for field in partial_child.__fields__.values(): # type: ignore + assert field.allow_none + assert not field.required + assert partial_child.__annotations__ == { + "foo": Optional[int], + "bar": Optional[int], + } + + +def test_partial_basemodel() -> None: + """ + Test that Partial returns no annotations for classes + that don't inherit from BaseModel. + """ + + class Foo: + bar: int + + # The type checker will raise a warning that Foo is not a BaseModel + # but we want to test for runtime behaviour in case someone passes in + # a class that doesn't inherit from BaseModel anyway. + with raises(ImproperlyConfiguredException): + Partial[Foo] # type: ignore
Partial doesn't work with inherited fields ```python from starlite import Partial, get from pydantic import BaseModel class Parent(BaseModel): foo: int class Child(Parent): bar: int @get("/test") def example(obj: Partial[Child]) -> None: print(obj) ``` In the above example, `Partial[Child]` only accepts the field `bar: Optional[int]` and ignores all fields from the superclass. I couldn't find this behaviour documented anywhere so I assume this isn't intended? ```python Python 3.10.5 (main, Jun 23 2022, 17:14:57) [Clang 13.1.6 (clang-1316.0.21.2.5)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from starlite import Partial >>> from pydantic import BaseModel >>> class Parent(BaseModel): ... foo: int ... >>> class Child(Parent): ... bar: int ... >>> PartialChild = Partial[Child] >>> PartialChild.__annotations__ {'bar': typing.Optional[int]} >>> ``` This behaviour can also be seen above
I believe the following implementation would work: ```python class Partial(Generic[T]): _models: Dict[Type[T], Any] = {} def __class_getitem__(cls, item: Type[T]) -> Type[T]: """ Modifies a given T subclass of BaseModel to be all optional """ if not cls._models.get(item): field_definitions: Dict[str, Tuple[Any, None]] = {} for obj in item.mro(): if issubclass(obj, BaseModel): for field_name, field_type in obj.__annotations__.items(): # we modify the field annotations to make it optional if not isinstance(field_type, GenericAlias) or type(None) not in field_type.__args__: field_definitions[field_name] = (Optional[field_type], None) else: field_definitions[field_name] = (field_type, None) else: break cls._models[item] = create_model(f"Partial{item.__name__}", **field_definitions) # type: ignore return cast(Type[T], cls._models.get(item)) ``` This implementation will traverse the class' mro and grab all annotations from parent classes until `BaseModel` is reached. This does, however, change the runtime behaviour of `Partial` since even though the linter complains, you can currently pass a non BaseModel class into Partial: ```python >>> from starlite import Partial >>> class Parent: ... foo: int ... bar: int ... >>> temp = Partial[Parent] >>> temp.__annotations__ {'foo': typing.Optional[int], 'bar': typing.Optional[int]} ``` Whereas, after this change the same code would simply produce `{}` as `Parent` is not a subclass of `pydantic.BaseModel`. Currently the documentation for this class says "Modifies a given T subclass of BaseModel to be all optional" so the new behaviour would be correct from that perspective. Great! Would you like to add a PR?
2022-07-18T19:31:29
litestar-org/litestar
336
litestar-org__litestar-336
[ "333" ]
4378e09c8eb5debb6caaa95a3dfea3477c4b6b2f
diff --git a/starlite/config.py b/starlite/config.py --- a/starlite/config.py +++ b/starlite/config.py @@ -12,7 +12,7 @@ ) from urllib.parse import urlencode -from pydantic import AnyUrl, BaseModel, DirectoryPath, constr, validator +from pydantic import AnyUrl, BaseConfig, BaseModel, DirectoryPath, constr, validator from pydantic_openapi_schema.utils import construct_open_api_with_schema_class from pydantic_openapi_schema.v3_1_0.contact import Contact from pydantic_openapi_schema.v3_1_0.external_documentation import ExternalDocumentation @@ -144,6 +144,9 @@ def dict(self, *args, **kwargs) -> Dict[str, Any]: # type: ignore[no-untyped-de class OpenAPIConfig(BaseModel): """Class containing Settings and Schema Properties""" + class Config(BaseConfig): + copy_on_model_validation = False + create_examples: bool = False openapi_controller: Type[OpenAPIController] = OpenAPIController @@ -214,8 +217,9 @@ class StaticFilesConfig(BaseModel): class TemplateConfig(BaseModel): - class Config: + class Config(BaseConfig): arbitrary_types_allowed = True + copy_on_model_validation = False directory: Union[DirectoryPath, List[DirectoryPath]] engine: Type[TemplateEngineProtocol] @@ -232,8 +236,9 @@ def default_cache_key_builder(request: "Request") -> str: class CacheConfig(BaseModel): - class Config: + class Config(BaseConfig): arbitrary_types_allowed = True + copy_on_model_validation = False backend: CacheBackendProtocol = SimpleCacheBackend() expiration: int = 60 # value in seconds diff --git a/starlite/exceptions/utils.py b/starlite/exceptions/utils.py --- a/starlite/exceptions/utils.py +++ b/starlite/exceptions/utils.py @@ -2,7 +2,7 @@ from pydantic import BaseModel from starlette.exceptions import HTTPException as StarletteHTTPException -from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR # noqa: TC002 +from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR from starlite.enums import MediaType from starlite.response import Response
diff --git a/test.sqlite b/test.sqlite new file mode 100644 Binary files /dev/null and b/test.sqlite differ diff --git a/tests/caching/__init__.py b/tests/caching/__init__.py new file mode 100644 --- /dev/null +++ b/tests/caching/__init__.py @@ -0,0 +1,20 @@ +import random +from typing import TYPE_CHECKING +from uuid import uuid4 + +if TYPE_CHECKING: + from starlite import Response + + +async def slow_handler() -> dict: + output = {} + count = 0 + while count < 1000: + output[str(count)] = random.random() + count += 1 + return output + + +def after_request_handler(response: "Response") -> "Response": + response.headers["unique-identifier"] = str(uuid4()) + return response diff --git a/tests/caching/test_async_caching.py b/tests/caching/test_async_caching.py new file mode 100644 --- /dev/null +++ b/tests/caching/test_async_caching.py @@ -0,0 +1,30 @@ +from typing import Any + +from starlite import CacheConfig, get +from starlite.cache import SimpleCacheBackend +from starlite.testing import create_test_client + +from . import after_request_handler, slow_handler + + +def test_async_handling() -> None: + class AsyncCacheBackend(SimpleCacheBackend): + async def set(self, key: str, value: Any, expiration: int) -> Any: # type: ignore + super().set(key=key, value=value, expiration=expiration) + + async def get(self, key: str) -> Any: + return super().get(key=key) + + cache_config = CacheConfig(backend=AsyncCacheBackend()) + + with create_test_client( + route_handlers=[get("/cached-async", cache=True)(slow_handler)], + after_request=after_request_handler, + cache_config=cache_config, + ) as client: + first_response = client.get("/cached-async") + first_response_identifier = first_response.headers["unique-identifier"] + assert first_response_identifier + second_response = client.get("/cached-async") + assert second_response.headers["unique-identifier"] == first_response_identifier + assert first_response.json() == second_response.json() diff --git a/tests/caching/test_config_validation.py b/tests/caching/test_config_validation.py new file mode 100644 --- /dev/null +++ b/tests/caching/test_config_validation.py @@ -0,0 +1,38 @@ +from typing import Any + +import pytest +import redis +from pydantic import ValidationError + +from starlite import CacheConfig, Starlite +from starlite.cache import CacheBackendProtocol + + +def test_config_validation_scenario() -> None: + class ProtocolBaseBackend(CacheBackendProtocol): + def get(self, key: str) -> None: + ... + + def set(self, key: str, value: Any, expiration: int) -> None: + ... + + CacheConfig(backend=ProtocolBaseBackend) # type: ignore[arg-type] + + class NoneProtocolBasedBackend: + def get(self, key: str) -> None: + ... + + def set(self, key: str, value: Any, expiration: int) -> None: + ... + + with pytest.raises(ValidationError): + CacheConfig(backend=NoneProtocolBasedBackend) # type: ignore[arg-type] + + +def test_config_validation_deep_copy() -> None: + """ + test fix for issue-333: https://github.com/starlite-api/starlite/issues/333 + """ + + cache_config = CacheConfig(backend=redis.from_url("redis://localhost:6379/1")) + Starlite(route_handlers=[], cache_config=cache_config) diff --git a/tests/test_caching.py b/tests/caching/test_response_caching.py similarity index 55% rename from tests/test_caching.py rename to tests/caching/test_response_caching.py --- a/tests/test_caching.py +++ b/tests/caching/test_response_caching.py @@ -1,30 +1,11 @@ -import random from datetime import datetime, timedelta -from time import sleep -from typing import Any -from uuid import uuid4 -import pytest from freezegun import freeze_time -from pydantic import ValidationError -from starlite import CacheConfig, Request, Response, get -from starlite.cache import SimpleCacheBackend +from starlite import Request, get from starlite.testing import create_test_client - -async def slow_handler() -> dict: - output = {} - count = 0 - while count < 1000: - output[str(count)] = random.random() - count += 1 - return output - - -def after_request_handler(response: Response) -> Response: - response.headers["unique-identifier"] = str(uuid4()) - return response +from . import after_request_handler, slow_handler def test_default_cache_response() -> None: @@ -67,7 +48,7 @@ def test_default_expiration() -> None: assert first_response.headers["unique-identifier"] != third_response.headers["unique-identifier"] -def test_cache_key() -> None: +def test_custom_cache_key() -> None: def custom_cache_key_builder(request: Request) -> str: return request.url.path + ":::cached" @@ -76,46 +57,3 @@ def custom_cache_key_builder(request: Request) -> str: ) as client: client.get("/cached") assert client.app.cache_config.backend.get("/cached:::cached") - - -def test_async_handling() -> None: - class AsyncCacheBackend(SimpleCacheBackend): - async def set(self, key: str, value: Any, expiration: int) -> Any: # type: ignore - super().set(key=key, value=value, expiration=expiration) - - async def get(self, key: str) -> Any: - return super().get(key=key) - - cache_config = CacheConfig(backend=AsyncCacheBackend()) - - with create_test_client( - route_handlers=[get("/cached-async", cache=True)(slow_handler)], - after_request=after_request_handler, - cache_config=cache_config, - ) as client: - first_response = client.get("/cached-async") - first_response_identifier = first_response.headers["unique-identifier"] - assert first_response_identifier - second_response = client.get("/cached-async") - assert second_response.headers["unique-identifier"] == first_response_identifier - assert first_response.json() == second_response.json() - - -def test_config_validation() -> None: - class MyBackend: - def get(self) -> None: - ... - - def set(self) -> None: - ... - - with pytest.raises(ValidationError): - CacheConfig(backend=MyBackend) # type: ignore[arg-type] - - -def test_naive_cache_backend() -> None: - backend = SimpleCacheBackend() - backend.set("test", "1", 0.1) # type: ignore - assert backend.get("test") - sleep(0.2) - assert not backend.get("test") diff --git a/tests/caching/test_simple_cache_backend.py b/tests/caching/test_simple_cache_backend.py new file mode 100644 --- /dev/null +++ b/tests/caching/test_simple_cache_backend.py @@ -0,0 +1,11 @@ +from time import sleep + +from starlite.cache import SimpleCacheBackend + + +def test_simple_cache_backend() -> None: + backend = SimpleCacheBackend() + backend.set("test", "1", 0.1) # type: ignore + assert backend.get("test") + sleep(0.2) + assert not backend.get("test") diff --git a/tests/test.sqlite b/tests/test.sqlite new file mode 100644 Binary files /dev/null and b/tests/test.sqlite differ
Pydantic 1.9.1 deepcopy breaks Redis caching, possibly other things I'm open to the possibility that this should be treated as an issue in Pydantic because it's a breaking change there, and https://github.com/samuelcolvin/pydantic/issues/4184 appears to be a variation of this. I have a Starlite application which configures its caching as follows (excerpt from my actual `app.py`): ```python import redis import starlite from .config import settings cache_config = ( starlite.CacheConfig(backend=redis.from_url(settings.CACHE_URL)) if settings.CACHE_URL is not None else starlite.app.DEFAULT_CACHE_CONFIG ) ``` `config.settings` in this case is a `pydantic.BaseSettings` instance which reads the Redis URL from an environment variable, if set. The fallback logic is for local development where a Redis instance may not be running. I recently did an upgrade of my dependency tree which moved from Pydantic 1.9.0 to Pydantic 1.9.1, and my web worker processes now fail to boot. Reverting to Pydantic 1.9.0 resolves this. The failure occurs at instantiating the `Starlite` application object: ```python File /opt/venv/lib/python3.10/site-packages/pydantic/decorator.py:40, in pydantic.decorator.validate_arguments.validate.wrapper_function() File /opt/venv/lib/python3.10/site-packages/pydantic/decorator.py:133, in pydantic.decorator.ValidatedFunction.call() File /opt/venv/lib/python3.10/site-packages/pydantic/decorator.py:130, in pydantic.decorator.ValidatedFunction.init_model_instance() File /opt/venv/lib/python3.10/site-packages/pydantic/main.py:341, in pydantic.main.BaseModel.__init__() ValidationError: 1 validation error for Init cache_config cannot pickle '_thread.lock' object (type=type_error) ``` The root of the issue appears to be that in Pydantic 1.9.1, Pydantic defaults to performing a `copy.deepcopy()` of model members during validation, which in turn fails on encountering any non-pickle-able object (as in the above traceback where it attempts to `deepcopy()` a Redis client instance). Pydantic 1.9.0 performed only a shallow copy. This behavior can be disabled by setting the `copy_on_model_validation` option to a false-y value in the config for a Pydantic model class, or by passing it in the `config` dictionary of the `validate_arguments` decorator, and that may be the simplest workaround to apply for now while Pydantic decides what to do about this. It may also be the correct long-term choice since it's likely that non-pickle-able objects, such as caching clients, will be passed in arguments to the `Starlite` constructor from time to time. This issue appears to be present in any version of Starlite which decorates `Starlite.__init__()` with `validate_arguments`, when using Pydantic 1.9.1 (I've tested Starlite 1.7.3 and 1.3.3), and disappears on reverting to Pydantic 1.9.0.
Ok, thanks for the analysis. Would you like to submit a PR? If you'd be OK with passing `"copy_on_model_validation": False` as the workaround, I can put together a PR for it in the next couple days. The tricky part will be the testing -- do you have a preference for a non-pickle-able object to pass to `Starlite` to verify the fix? Absolutely Here's a repro for the pydantic side: ```python import tempfile from typing import Any import pydantic class Container(pydantic.BaseModel): fh: Any @pydantic.validate_arguments(config={"copy_on_model_validation": False}) def receives_container(container: Container) -> None: ... with tempfile.TemporaryFile() as fh: receives_container(Container(fh=fh)) ``` Results in: ```python-traceback Traceback (most recent call last): File "/home/peter/PycharmProjects/copy-on-model-validation/main.py", line 17, in <module> receives_container(Container(fh=fh)) File "pydantic/decorator.py", line 40, in pydantic.decorator.validate_arguments.validate.wrapper_function File "pydantic/decorator.py", line 133, in pydantic.decorator.ValidatedFunction.call File "pydantic/decorator.py", line 130, in pydantic.decorator.ValidatedFunction.init_model_instance File "pydantic/main.py", line 341, in pydantic.main.BaseModel.__init__ pydantic.error_wrappers.ValidationError: 1 validation error for ReceivesContainer container cannot pickle '_io.BufferedRandom' object (type=type_error) ``` I created that as I found this issue: https://github.com/samuelcolvin/pydantic/issues/3284 and wanted a quick test.. and as that issue suggests `@pydantic.validate_arguments(config={"copy_on_model_validation": False})` has no effect. Setting it on the `Config` object on `Container` does fix it. Well, if passing it to `validate_arguments` doesn't actually work, then I guess I won't try that. So whats the solution? we strip validate arguments or we pin to 1.9? Or is there an alternative? As a user, I'm pinning to Pydantic 1.9.0 until they decide what they're going to do about it. I'm not sure, and I don't presume to tell you, what the best choice is for Starlite -- both pinning and remove `validate_arguments` seem like they have downsides. We should probably set `copy_on_model_validation = False` on `CacheConfig.Config` to address this specific case, and see if any other issues arise. It's not as if `1.9.1` is a new release, so there's unlikely to be many more similar issues in my opinion.
2022-08-05T07:44:30
litestar-org/litestar
392
litestar-org__litestar-392
[ "428" ]
2e3a22c099bcede3f11ac1c1c856dc3bc73bd2f8
diff --git a/examples/__init__.py b/examples/__init__.py new file mode 100644 diff --git a/examples/hello_world.py b/examples/hello_world.py new file mode 100644 --- /dev/null +++ b/examples/hello_world.py @@ -0,0 +1,11 @@ +"""Minimal Starlite application.""" +from starlite import Starlite, get + + +@get("/") +def hello_world() -> dict[str, str]: + """Hi.""" + return {"hello": "world"} + + +app = Starlite(route_handlers=[hello_world]) diff --git a/examples/startup_and_shutdown.py b/examples/startup_and_shutdown.py new file mode 100644 --- /dev/null +++ b/examples/startup_and_shutdown.py @@ -0,0 +1,33 @@ +from typing import cast + +from pydantic import BaseSettings +from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine + +from starlite import Starlite, State + + +class AppSettings(BaseSettings): + DATABASE_URI: str = "postgresql+asyncpg://postgres:[email protected]:5432/db" + + +settings = AppSettings() + + +def get_db_connection(state: State) -> AsyncEngine: + """Returns the db engine. + + If it doesn't exist, creates it and saves it in on the application + state object + """ + if not getattr(state, "engine", None): + state.engine = create_async_engine(settings.DATABASE_URI) + return cast("AsyncEngine", state.engine) + + +async def close_db_connection(state: State) -> None: + """Closes the db connection stored in the application State object.""" + if getattr(state, "engine", None): + await cast("AsyncEngine", state.engine).dispose() + + +app = Starlite(route_handlers=[], on_startup=[get_db_connection], on_shutdown=[close_db_connection])
diff --git a/examples/tests/__init__.py b/examples/tests/__init__.py new file mode 100644 diff --git a/examples/tests/test_hello_world.py b/examples/tests/test_hello_world.py new file mode 100644 --- /dev/null +++ b/examples/tests/test_hello_world.py @@ -0,0 +1,11 @@ +from starlette.status import HTTP_200_OK + +from examples import hello_world +from starlite.testing import TestClient + + +def test_hello_world_example() -> None: + with TestClient(app=hello_world.app) as client: + r = client.get("/") + assert r.status_code == HTTP_200_OK + assert r.json() == {"hello": "world"} diff --git a/examples/tests/test_startup_and_shutdown.py b/examples/tests/test_startup_and_shutdown.py new file mode 100644 --- /dev/null +++ b/examples/tests/test_startup_and_shutdown.py @@ -0,0 +1,29 @@ +from typing import TYPE_CHECKING +from unittest.mock import AsyncMock, MagicMock + +from examples import startup_and_shutdown +from starlite import State, get +from starlite.testing import TestClient + +if TYPE_CHECKING: + from pytest import MonkeyPatch # noqa:PT013 + + +class FakeAsyncEngine: + dispose = AsyncMock() + + +async def test_startup_and_shutdown_example(monkeypatch: "MonkeyPatch") -> None: + + monkeypatch.setattr(startup_and_shutdown, "create_async_engine", MagicMock(return_value=FakeAsyncEngine)) + + @get("/") + def handler(state: State) -> None: + assert state.engine is FakeAsyncEngine + return None + + startup_and_shutdown.app.register(handler) + + with TestClient(app=startup_and_shutdown.app) as client: + client.get("/") + FakeAsyncEngine.dispose.assert_awaited_once()
Dependency: Brotli missing from test dependencies All `full` extras dependencies are available in dev-deps, except for `brotli`. To reproduce: ```shell $ poetry env remove python $ poetry install $ poetry run pytest . ``` This should mean we don't need to require `poetry install -extras full` in `CONTRIBUTING.md` and `ci.yaml`
2022-08-21T12:16:10
litestar-org/litestar
426
litestar-org__litestar-426
[ "424" ]
09ff5535684c0b28d134189bbc4f4b947e2ab715
diff --git a/starlite/app.py b/starlite/app.py --- a/starlite/app.py +++ b/starlite/app.py @@ -77,7 +77,7 @@ class HandlerIndex(TypedDict): path: str """Full route path to the route handler.""" - handler: Union[Union["HTTPRouteHandler", "WebsocketRouteHandler", "ASGIRouteHandler"]] + handler: Union["HTTPRouteHandler", "WebsocketRouteHandler", "ASGIRouteHandler"] """Route handler instance.""" diff --git a/starlite/middleware/authentication.py b/starlite/middleware/authentication.py --- a/starlite/middleware/authentication.py +++ b/starlite/middleware/authentication.py @@ -1,13 +1,12 @@ +import re from abc import ABC, abstractmethod -from typing import TYPE_CHECKING, Any, Union +from typing import TYPE_CHECKING, Any, List, Optional, Pattern, Union from pydantic import BaseConfig, BaseModel from starlette.requests import HTTPConnection -from starlite.enums import MediaType, ScopeType -from starlite.exceptions import NotAuthorizedException, PermissionDeniedException +from starlite.enums import ScopeType from starlite.middleware.base import MiddlewareProtocol -from starlite.response import Response if TYPE_CHECKING: from starlette.types import ASGIApp, Receive, Scope, Send @@ -34,56 +33,35 @@ class AbstractAuthenticationMiddleware(ABC, MiddlewareProtocol): """ Scopes supported by the middleware. """ - error_response_media_type = MediaType.JSON - """ - The 'Content-Type' to use for error responses. - """ - websocket_error_status_code = 4000 - """ - The status code to for websocket authentication errors. - """ - def __init__(self, app: "ASGIApp"): + def __init__( + self, + app: "ASGIApp", + exclude: Optional[Union[str, List[str]]] = None, + ): """This is an abstract AuthenticationMiddleware that allows users to create their own AuthenticationMiddleware by extending it and overriding the 'authenticate_request' method. Args: app: An ASGIApp, this value is the next ASGI handler to call in the middleware stack. + exclude: A pattern or list of patterns to skip in the authentication middleware. """ super().__init__(app) self.app = app + self.exclude: Optional[Pattern[str]] = None + if exclude: + self.exclude = re.compile("|".join(exclude)) if isinstance(exclude, list) else re.compile(exclude) async def __call__(self, scope: "Scope", receive: "Receive", send: "Send") -> None: - try: + if self.exclude and self.exclude.findall(scope["path"]): + await self.app(scope, receive, send) + else: if scope["type"] in self.scopes: auth_result = await self.authenticate_request(HTTPConnection(scope)) scope["user"] = auth_result.user scope["auth"] = auth_result.auth await self.app(scope, receive, send) - except (NotAuthorizedException, PermissionDeniedException) as e: - if scope["type"] == ScopeType.WEBSOCKET: # pragma: no cover - await send({"type": "websocket.close", "code": self.websocket_error_status_code, "reason": repr(e)}) - else: - response = self.create_error_response(exc=e) - await response(scope, receive, send) - - def create_error_response(self, exc: Union[NotAuthorizedException, PermissionDeniedException]) -> Response: - """Creates an Error response from the given exceptions, defaults to a - JSON response. - - Args: - exc: Either an [NotAuthorizedException][starlite.exceptions.NotAuthorizedException] or - [PermissionDeniedException][starlite.exceptions.PermissionDeniedException] instance. - - Returns: - A [Response][starlite.response.Response] instance. - """ - return Response( - media_type=self.error_response_media_type, - content={"detail": exc.detail, "extra": exc.extra}, - status_code=exc.status_code, - ) @abstractmethod async def authenticate_request(self, request: HTTPConnection) -> AuthenticationResult: # pragma: no cover diff --git a/starlite/types.py b/starlite/types.py --- a/starlite/types.py +++ b/starlite/types.py @@ -56,7 +56,11 @@ H = TypeVar("H", bound=HTTPConnection) Middleware = Union[ - StarletteMiddleware, DefineMiddleware, Type[BaseHTTPMiddleware], Type[MiddlewareProtocol], Callable[..., ASGIApp] + StarletteMiddleware, + DefineMiddleware, + Type[BaseHTTPMiddleware], + Type[MiddlewareProtocol], + Callable[..., ASGIApp], ] ResponseType = Type[Response] ExceptionHandler = Callable[
diff --git a/tests/middleware/test_authentication.py b/tests/middleware/test_authentication.py --- a/tests/middleware/test_authentication.py +++ b/tests/middleware/test_authentication.py @@ -1,4 +1,4 @@ -from typing import TYPE_CHECKING, Dict +from typing import TYPE_CHECKING, Any, Dict import pytest from pydantic import BaseModel @@ -16,12 +16,17 @@ AbstractAuthenticationMiddleware, AuthenticationResult, ) +from starlite.middleware.base import DefineMiddleware from starlite.testing import create_test_client if TYPE_CHECKING: from starlette.requests import HTTPConnection +async def dummy_app(scope: Any, receive: Any, send: Any) -> None: + return None + + class User(BaseModel): name: str id: int @@ -124,3 +129,32 @@ async def route_handler(socket: WebSocket[User, Auth]) -> None: client = create_test_client(route_handlers=route_handler) with pytest.raises(WebSocketDisconnect), client.websocket_connect("/", headers={"Authorization": "yep"}) as ws: ws.receive_json() + + +def test_authentication_middleware_exclude() -> None: + auth_mw = DefineMiddleware(AuthMiddleware, exclude=["north", "south"]) + + @get("/north/{value:int}") + def north_handler(value: int) -> Dict[str, int]: + return {"value": value} + + @get("/south") + def south_handler() -> None: + return None + + @get("/west") + def west_handler() -> None: + return None + + with create_test_client( + route_handlers=[north_handler, south_handler, west_handler], + middleware=[auth_mw], + ) as client: + response = client.get("/north/1") + assert response.status_code == HTTP_200_OK + + response = client.get("/south") + assert response.status_code == HTTP_200_OK + + response = client.get("/west") + assert response.status_code == HTTP_403_FORBIDDEN
Abstract Authentication Middleware should respect `error_handlers` defined at the app/router level? Should the `AbstractAuthenticationMiddleware` use the `exception_handlers`? Given the example below, the `exeption_formatter` is not called for `NotAuthorized` exception, and you have to override the `error_response` method to return the custom exception format. ```python from typing import Union from pydantic import BaseModel from starlette.requests import HTTPConnection from starlite import ( AbstractAuthenticationMiddleware, AuthenticationResult, Controller, HTTPException, MediaType, NotAuthorizedException, Request, Response, Router, Starlite, get, ) from starlite.exceptions.exceptions import PermissionDeniedException class ExceptionResponse(BaseModel): status_code: int message: str def exception_formatter(_: Request, exception: Exception) -> Response: return Response( content=ExceptionResponse( status_code=getattr(exception, "status_code", 500), message=getattr(exception, "detail", "") ), status_code=getattr(exception, "status_code", 500), media_type=MediaType.JSON, ) class AuthenticationMiddleware(AbstractAuthenticationMiddleware): async def authenticate_request(self, request: HTTPConnection) -> AuthenticationResult: if not (token := request.headers.get("Authorization")): raise NotAuthorizedException() return AuthenticationResult(user=None, auth=token) class MyController(Controller): path = "/needs-auth" @get() async def needs_auth(self) -> str: return "needs auth token" router = Router( path="/api", route_handlers=[MyController], middleware=[AuthenticationMiddleware], ) app = Starlite( route_handlers=[router], exception_handlers={HTTPException: exception_formatter}, ) ```
2022-08-29T02:51:23
litestar-org/litestar
431
litestar-org__litestar-431
[ "371" ]
09ff5535684c0b28d134189bbc4f4b947e2ab715
diff --git a/starlite/app.py b/starlite/app.py --- a/starlite/app.py +++ b/starlite/app.py @@ -1,3 +1,4 @@ +from pathlib import Path from typing import TYPE_CHECKING, Dict, List, Optional, Set, Union, cast from pydantic import validate_arguments @@ -7,7 +8,12 @@ from starlette.middleware.trustedhost import TrustedHostMiddleware from typing_extensions import TypedDict -from starlite.asgi import PathParamPlaceholder, RouteMapNode, StarliteASGIRouter +from starlite.asgi import ( + PathParameterTypePathDesignator, + PathParamNode, + RouteMapNode, + StarliteASGIRouter, +) from starlite.config import ( CacheConfig, CompressionConfig, @@ -277,6 +283,7 @@ def register(self, value: ControllerRouterHandler) -> None: # type: ignore[over else: route_handlers = [cast("Union[WebSocketRoute, ASGIRoute]", route).route_handler] # type: ignore for route_handler in route_handlers: + self._create_handler_signature_model(route_handler=route_handler) route_handler.resolve_guards() route_handler.resolve_middleware() @@ -360,8 +367,11 @@ def _add_node_to_route_map(self, route: BaseRoute) -> RouteMapNode: components_set = cast("ComponentsSet", current_node["_components"]) if isinstance(component, dict): + # The rest of the path should be regarded as a parameter value. + if component["type"] is Path: + components_set.add(PathParameterTypePathDesignator) # Represent path parameters using a special value - component = PathParamPlaceholder + component = PathParamNode components_set.add(component) diff --git a/starlite/asgi.py b/starlite/asgi.py --- a/starlite/asgi.py +++ b/starlite/asgi.py @@ -1,6 +1,28 @@ +import re +from datetime import date, datetime, time, timedelta +from decimal import Decimal from inspect import getfullargspec, isawaitable, ismethod -from typing import TYPE_CHECKING, Any, Dict, List, Set, Tuple, Type, Union, cast +from pathlib import Path +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + List, + Set, + Tuple, + Type, + Union, + cast, +) +from uuid import UUID +from pydantic.datetime_parse import ( + parse_date, + parse_datetime, + parse_duration, + parse_time, +) from starlette.routing import Router as StarletteRouter from starlite.enums import ScopeType @@ -18,13 +40,18 @@ from starlite.types import LifeCycleHandler -class PathParamPlaceholder: +class PathParamNode: """Sentinel object to represent a path param in the route map.""" -PathParamPlaceholderType = Type[PathParamPlaceholder] +class PathParameterTypePathDesignator: + """Sentinel object to a path parameter of type 'path'.""" + + +PathParamPlaceholderType = Type[PathParamNode] +TerminusNodePlaceholderType = Type[PathParameterTypePathDesignator] RouteMapNode = Dict[Union[str, PathParamPlaceholderType], Any] -ComponentsSet = Set[Union[str, PathParamPlaceholderType]] +ComponentsSet = Set[Union[str, PathParamPlaceholderType, TerminusNodePlaceholderType]] class StarliteASGIRouter(StarletteRouter): @@ -44,12 +71,20 @@ def _traverse_route_map(self, path: str, scope: "Scope") -> Tuple[RouteMapNode, """Traverses the application route mapping and retrieves the correct node for the request url. - Raises NotFoundException if no correlating node is found + Args: + path: The request's path. + scope: The ASGI connection scope. + + Raises: + NotFoundException: if no correlating node is found. + + Returns: + A tuple containing the target RouteMapNode and a list containing all path parameter values. """ path_params: List[str] = [] current_node = self.app.route_map components = ["/", *[component for component in path.split("/") if component]] - for component in components: + for idx, component in enumerate(components): components_set = cast("ComponentsSet", current_node["_components"]) if component in components_set: current_node = cast("RouteMapNode", current_node[component]) @@ -57,9 +92,12 @@ def _traverse_route_map(self, path: str, scope: "Scope") -> Tuple[RouteMapNode, self._handle_static_path(scope=scope, node=current_node) break continue - if PathParamPlaceholder in components_set: + if PathParamNode in components_set: + current_node = cast("RouteMapNode", current_node[PathParamNode]) + if PathParameterTypePathDesignator in components_set: + path_params.append("/".join(path.split("/")[idx:])) + break path_params.append(component) - current_node = cast("RouteMapNode", current_node[PathParamPlaceholder]) continue raise NotFoundException() return current_node, path_params @@ -70,7 +108,7 @@ def _handle_static_path(scope: "Scope", node: RouteMapNode) -> None: work as expected. Args: - scope: Request Scope + scope: The ASGI connection scope. node: Trie Node Returns: @@ -92,19 +130,32 @@ def _parse_path_parameters( request_path_parameter_values: A list of raw strings sent as path parameters as part of the request Raises: - ValidationException + ValidationException: if path parameter parsing fails Returns: A dictionary mapping path parameter names to parsed values """ result: Dict[str, Any] = {} + parsers_map: Dict[Any, Callable] = { + str: str, + float: float, + int: int, + Decimal: Decimal, + UUID: UUID, + Path: lambda x: Path(re.sub("//+", "", (x.lstrip("/")))), + date: parse_date, + datetime: parse_datetime, + time: parse_time, + timedelta: parse_duration, + } try: for idx, parameter_definition in enumerate(path_parameter_definitions): raw_param_value = request_path_parameter_values[idx] parameter_type = parameter_definition["type"] parameter_name = parameter_definition["name"] - result[parameter_name] = parameter_type(raw_param_value) + parser = parsers_map[parameter_type] + result[parameter_name] = parser(raw_param_value) return result except (ValueError, TypeError, KeyError) as e: # pragma: no cover raise ValidationException( diff --git a/starlite/routes/base.py b/starlite/routes/base.py --- a/starlite/routes/base.py +++ b/starlite/routes/base.py @@ -1,5 +1,8 @@ import re from abc import ABC, abstractmethod +from datetime import date, datetime, time, timedelta +from decimal import Decimal +from pathlib import Path from typing import TYPE_CHECKING, List, Optional, Tuple, Type, Union from uuid import UUID @@ -19,7 +22,18 @@ param_match_regex = re.compile(r"{(.*?)}") -param_type_map = {"str": str, "int": int, "float": float, "uuid": UUID} +param_type_map = { + "str": str, + "int": int, + "float": float, + "uuid": UUID, + "decimal": Decimal, + "date": date, + "datetime": datetime, + "time": time, + "timedelta": timedelta, + "path": Path, +} class PathParameterDefinition(TypedDict): @@ -123,7 +137,7 @@ def _validate_path_parameter(param: str) -> None: raise ImproperlyConfiguredException("Path parameter names should be of length greater than zero") if param_type not in param_type_map: raise ImproperlyConfiguredException( - "Path parameters should be declared with an allowed type, i.e. 'str', 'int', 'float' or 'uuid'" + f"Path parameters should be declared with an allowed type, i.e. one of {','.join(param_type_map.keys())}" ) @classmethod
diff --git a/tests/kwargs/test_path_params.py b/tests/kwargs/test_path_params.py --- a/tests/kwargs/test_path_params.py +++ b/tests/kwargs/test_path_params.py @@ -1,3 +1,7 @@ +from datetime import date, datetime, timedelta +from decimal import Decimal +from pathlib import Path +from typing import Any from uuid import uuid1, uuid4 import pytest @@ -100,7 +104,7 @@ def test_method( def test_path_param_validation(path: str) -> None: @get(path=path) def test_method() -> None: - pass + raise AssertionError("should not be called") with pytest.raises(ImproperlyConfiguredException): Starlite(route_handlers=[test_method]) @@ -108,8 +112,41 @@ def test_method() -> None: def test_duplicate_path_param_validation() -> None: @get(path="/{param:int}/foo/{param:int}") - def test_method(param: int) -> None: - pass + def test_method() -> None: + raise AssertionError("should not be called") with pytest.raises(ImproperlyConfiguredException): Starlite(route_handlers=[test_method]) + + [email protected]( + "param_type_name, param_type_class, value", + [ + # ["str", str, "abc"], + # ["int", int, 1], + # ["float", float, 1.01], + # ["uuid", UUID, uuid4()], + # ["decimal", Decimal, Decimal("1.00001")], + # ["date", date, date.today().isoformat()], + # ["datetime", datetime, datetime.now().isoformat()], + # ["timedelta", timedelta, timedelta(days=1).total_seconds()], + ["path", Path, "/1/2/3/4/some-file.txt"], + ], +) +def test_path_param_type_resolution(param_type_name: str, param_type_class: Any, value: Any) -> None: + @get("/some/test/path/{test:" + param_type_name + "}") + def handler(test: param_type_class) -> None: # type: ignore + if isinstance(test, (date, datetime)): + assert test.isoformat() == value # type: ignore + elif isinstance(test, timedelta): # type: ignore + assert test.total_seconds() == value + elif isinstance(test, Decimal): + assert str(test) == str(value) + elif isinstance(test, Path): + assert str(test) == "1/2/3/4/some-file.txt" + else: + assert test == value + + with create_test_client(handler) as client: + response = client.get("/some/test/path/" + str(value)) + assert response.status_code == HTTP_200_OK diff --git a/tests/routing/test_route_map.py b/tests/routing/test_route_map.py --- a/tests/routing/test_route_map.py +++ b/tests/routing/test_route_map.py @@ -8,7 +8,7 @@ from hypothesis.strategies import DrawFn from starlite import HTTPRoute, get -from starlite.asgi import PathParamPlaceholder, PathParamPlaceholderType, RouteMapNode +from starlite.asgi import PathParamNode, PathParamPlaceholderType, RouteMapNode from starlite.middleware.exceptions import ExceptionHandlerMiddleware from starlite.testing import create_test_client @@ -25,7 +25,7 @@ def is_path_in_route_map(route_map: RouteMapNode, path: str, path_params: Set[st [ "/", *[ - PathParamPlaceholder if param_pattern.fullmatch(component) else component + PathParamNode if param_pattern.fullmatch(component) else component for component in path.split("/") if component ],
Enhancement: Add 'path' type to path parameters Starlette's route path parameters include a `path` type that matches any further path components. Example: `Route('/uploaded/{rest_of_path:path}', uploaded)` would match `/uploaded/some-dir/some-file.txt` with `rest_of_path` set to `some-dir/some-file.txt`. A couple cases where this might be useful: - A file upload service where uploaded files are exposed as a virtual directory tree - A blog where posts have extra path components for readability and SEO which are otherwise ignored, like `/posts/1234/2022/8/14/how-to-use-path-parameters/` with only `/posts/1234` being necessary It doesn't look like this is supported yet in Starlite. Is there a recommended approach in the meantime?
Not at present. I'm not sure how simple this is with our routing system. I looked through the routing code and it should be relatively simple to add this. However, I did discover a couple bugs I will create a separate issue for. Great, if you are confident, a PR is welcome 😉 @waweber do you intend to add this?
2022-08-29T13:46:12
litestar-org/litestar
445
litestar-org__litestar-445
[ "443" ]
fe52cdec5b7f16b9050de754953ae2d089a7939c
diff --git a/starlite/signature.py b/starlite/signature.py --- a/starlite/signature.py +++ b/starlite/signature.py @@ -39,6 +39,8 @@ UNDEFINED_SENTINELS = {Undefined, Signature.empty} +SKIP_NAMES = {"self", "cls"} +SKIP_VALIDATION_NAMES = {"request", "socket", "state"} class SignatureModel(BaseModel): @@ -203,10 +205,6 @@ class SignatureModelFactory: "plugins", "signature", ) - # names of fn params not included in signature model. - SKIP_NAMES = {"self", "cls"} - # names of params always typed `Any`. - SKIP_VALIDATION_NAMES = {"request", "socket"} def __init__(self, fn: "AnyCallable", plugins: List["PluginProtocol"], dependency_names: Set[str]) -> None: if fn is None: @@ -321,7 +319,7 @@ def signature_parameters(self) -> Generator[SignatureParameter, None, None]: Generator[SignatureParameter, None, None] """ for name, parameter in self.signature.parameters.items(): - if name in self.SKIP_NAMES: + if name in SKIP_NAMES: continue yield SignatureParameter(self.fn_name, name, parameter) @@ -335,7 +333,7 @@ def should_skip_parameter_validation(self, parameter: SignatureParameter) -> boo Returns: A boolean indicating whether injected values for this parameter should not be validated. """ - return parameter.name in self.SKIP_VALIDATION_NAMES or should_skip_dependency_validation(parameter.default) + return parameter.name in SKIP_VALIDATION_NAMES or should_skip_dependency_validation(parameter.default) def create_signature_model(self) -> Type[SignatureModel]: """Constructs a `SignatureModel` type that represents the signature of
diff --git a/tests/kwargs/test_reserved_kwargs_injection.py b/tests/kwargs/test_reserved_kwargs_injection.py --- a/tests/kwargs/test_reserved_kwargs_injection.py +++ b/tests/kwargs/test_reserved_kwargs_injection.py @@ -1,4 +1,4 @@ -from typing import Any, List, Optional, cast +from typing import Any, List, Optional, Type, Union, cast import pytest from pydantic import BaseModel, Field @@ -21,12 +21,18 @@ from tests import Person, PersonFactory -def test_application_state_injection() -> None: +class CustomState(State): + called: bool + msg: str + + [email protected]("state_typing", [State, CustomState]) +def test_application_state_injection(state_typing: Union[Type[State], CustomState]) -> None: @get("/", media_type=MediaType.TEXT) - def route_handler(state: State) -> str: + def route_handler(state: state_typing) -> str: # type: ignore assert state - state.called = True # this should not modify the app state - return cast("str", state.msg) # this shows injection worked + state.called = True # type: ignore + return cast("str", state.msg) # type: ignore with create_test_client(route_handler) as client: client.app.state.msg = "hello" diff --git a/tests/kwargs/test_validations.py b/tests/kwargs/test_validations.py --- a/tests/kwargs/test_validations.py +++ b/tests/kwargs/test_validations.py @@ -16,6 +16,7 @@ websocket, ) from starlite.constants import RESERVED_KWARGS +from starlite.signature import SKIP_VALIDATION_NAMES def my_dependency() -> int: @@ -90,7 +91,7 @@ def test_raises_when_reserved_kwargs_are_misused(reserved_kwarg: str) -> None: # these kwargs are set to Any when the signature model is generated, # because pydantic can't handle generics for non pydantic classes. So these tests won't work for aliased parameters. - if reserved_kwarg not in ["socket", "request"]: + if reserved_kwarg not in SKIP_VALIDATION_NAMES: exec(f"async def test_fn({reserved_kwarg}: int = Parameter(query='my_param')) -> None: pass") handler_with_aliased_param = decorator("/")(locals()["test_fn"]) with pytest.raises(ImproperlyConfiguredException):
Bug: cannot use custom typed state Pydantic validation fails for custom typed state: ```python from starlite import State, get class MyState(State): my_value: int @get("/path") def handler(state: MyState) -> None: return None ``` This will raise a validation error.
2022-09-01T18:43:47
litestar-org/litestar
447
litestar-org__litestar-447
[ "414" ]
97cbd8ecaaf9c2cacfda32aadd15fd4de97ed413
diff --git a/starlite/logging/__init__.py b/starlite/logging/__init__.py --- a/starlite/logging/__init__.py +++ b/starlite/logging/__init__.py @@ -1,11 +1,16 @@ from logging import config -from typing import Any, Dict, List, Optional, Union +from typing import Any, Dict, Generator, Iterable, List, Optional, Union from pydantic import BaseModel from typing_extensions import Literal from starlite.logging.standard import QueueListenerHandler +try: + from picologging import config as picologging_config +except ImportError: + picologging_config = None + __all__ = ["LoggingConfig", "QueueListenerHandler"] @@ -49,5 +54,33 @@ class LoggingConfig(BaseModel): except that the propagate setting will not be applicable.""" def configure(self) -> None: - """Configured logger with the given configuration.""" + """Configured logger with the given configuration. + + If the logger class contains the word `picologging`, we try to + import and set the dictConfig + """ + for logging_class in find_keys(self.handlers, "class"): + if "picologging" in logging_class and picologging_config: + picologging_config.dictConfig(self.dict(exclude_none=True)) + break config.dictConfig(self.dict(exclude_none=True)) + + +def find_keys(node: Union[List, Dict], key: str) -> Generator[Iterable, None, None]: + """Find Nested Keys with name + Search a dictionary for the presence of key + Args: + node (Union[List, Dict]): a dictionary to search + key (str): the dictionary key to find + + Yields: + Generator[Iterable, None, None]: Value of dictionary key + """ + if isinstance(node, list): + for list_entry in node: + yield from find_keys(list_entry, key) + elif isinstance(node, dict): + if key in node: + yield node[key] + for dict_entry in node.values(): + yield from find_keys(dict_entry, key) diff --git a/starlite/logging/picologging.py b/starlite/logging/picologging.py --- a/starlite/logging/picologging.py +++ b/starlite/logging/picologging.py @@ -18,7 +18,7 @@ def __init__(self, handlers: List[Any], respect_handler_level: bool = False, que Args: handlers (list): list of handler names. - respect_handler_level (bool): A handler’s level is respected (compared with the level for the message) when + respect_handler_level (bool): A handler's level is respected (compared with the level for the message) when deciding whether to pass messages to that handler. """ super().__init__(queue) diff --git a/starlite/logging/standard.py b/starlite/logging/standard.py --- a/starlite/logging/standard.py +++ b/starlite/logging/standard.py @@ -13,7 +13,7 @@ def __init__(self, handlers: List[Any], respect_handler_level: bool = False, que Args: handlers (list): list of handler names. - respect_handler_level (bool): A handler’s level is respected (compared with the level for the message) when + respect_handler_level (bool): A handler's level is respected (compared with the level for the message) when deciding whether to pass messages to that handler. """ super().__init__(queue)
diff --git a/tests/logging_config/test_picologging.py b/tests/logging_config/test_picologging.py --- a/tests/logging_config/test_picologging.py +++ b/tests/logging_config/test_picologging.py @@ -32,6 +32,26 @@ def test_logging_debug(dict_config_mock: Mock) -> None: dict_config_mock.reset_mock() +@patch("picologging.config.dictConfig") +def test_picologging_dictconfig_debug(dict_config_mock: Mock) -> None: + log_config = LoggingConfig( + handlers={ + "console": { + "class": "picologging.StreamHandler", + "level": "DEBUG", + "formatter": "standard", + }, + "queue_listener": { + "class": "starlite.logging.picologging.QueueListenerHandler", + "handlers": ["cfg://handlers.console"], + }, + } + ) + log_config.configure() + assert dict_config_mock.mock_calls[0][1][0]["loggers"]["starlite"]["level"] == "INFO" + dict_config_mock.reset_mock() + + @patch("logging.config.dictConfig") def test_logging_startup(dict_config_mock: Mock) -> None: test_logger = LoggingConfig( @@ -52,7 +72,37 @@ def test_logging_startup(dict_config_mock: Mock) -> None: assert dict_config_mock.called +@patch("picologging.config.dictConfig") +def test_picologging_dictconfig_startup(dict_config_mock: Mock) -> None: + test_logger = LoggingConfig( + handlers={ + "console": { + "class": "picologging.StreamHandler", + "level": "DEBUG", + "formatter": "standard", + }, + "queue_listener": { + "class": "starlite.logging.picologging.QueueListenerHandler", + "handlers": ["cfg://handlers.console"], + }, + }, + loggers={"app": {"level": "INFO", "handlers": ["console"]}}, + ) + with create_test_client([], on_startup=[test_logger.configure]): + assert dict_config_mock.called + + +@patch("picologging.config.dictConfig") +def test_picologging_dictconfig_when_disabled(dict_config_mock: Mock) -> None: + test_logger = LoggingConfig( + loggers={"app": {"level": "INFO", "handlers": ["console"]}}, + ) + with create_test_client([], on_startup=[test_logger.configure]): + assert not dict_config_mock.called + + logger = logging.getLogger() + config = LoggingConfig( handlers={ "console": { @@ -67,6 +117,7 @@ def test_logging_startup(dict_config_mock: Mock) -> None: } ) config.configure() +picologger = picologging.getLogger() def test_queue_logger(caplog: "LogCaptureFixture") -> None: @@ -101,4 +152,8 @@ def test_logger_startup(caplog: "LogCaptureFixture") -> None: client.options("/") test_logger = logging.getLogger() handlers = test_logger.handlers + + test_picologging_logger = picologging.getLogger() + test_picologging_handlers = test_picologging_logger.handlers assert isinstance(handlers[0].handlers[0], picologging.StreamHandler) # type: ignore + assert isinstance(test_picologging_handlers[0].handlers[0], picologging.StreamHandler)
Enhancement: Support dictConfig in picologging `picologging` will implement a `dictConfig` with the following PR: https://github.com/microsoft/picologging/issues/53 We should enhance our integration to call this method once it's officially released.
The picologging [PR](https://github.com/microsoft/picologging/pull/61) is closed.
2022-09-01T21:34:38
litestar-org/litestar
472
litestar-org__litestar-472
[ "458" ]
945239079d6fe69be1ef32885fefd08c5808f855
diff --git a/starlite/response.py b/starlite/response.py --- a/starlite/response.py +++ b/starlite/response.py @@ -1,3 +1,4 @@ +from pathlib import PurePath, PurePosixPath from typing import ( TYPE_CHECKING, Any, @@ -12,7 +13,7 @@ import yaml from orjson import OPT_INDENT_2, OPT_OMIT_MICROSECONDS, OPT_SERIALIZE_NUMPY, dumps -from pydantic import BaseModel +from pydantic import BaseModel, SecretStr from pydantic_openapi_schema.v3_1_0.open_api import OpenAPI from starlette.responses import Response as StarletteResponse from starlette.status import HTTP_204_NO_CONTENT, HTTP_304_NOT_MODIFIED @@ -61,7 +62,7 @@ def __init__( self.cookies = cookies or [] @staticmethod - def serializer(value: Any) -> Dict[str, Any]: + def serializer(value: Any) -> Union[Dict[str, Any], str]: """Serializer hook for orjson to handle pydantic models. This method can be overridden to extend json serialization. @@ -74,6 +75,10 @@ def serializer(value: Any) -> Dict[str, Any]: """ if isinstance(value, BaseModel): return value.dict() + if isinstance(value, SecretStr): + return value.get_secret_value() + if isinstance(value, (PurePath, PurePosixPath)): + return str(value) raise TypeError # pragma: no cover def render(self, content: Any) -> bytes:
diff --git a/tests/response/test_serialization.py b/tests/response/test_serialization.py --- a/tests/response/test_serialization.py +++ b/tests/response/test_serialization.py @@ -1,13 +1,23 @@ +import enum from json import loads +from pathlib import PurePath from typing import Any, Dict, List import pytest +from pydantic import SecretStr from starlette.status import HTTP_200_OK from starlite import MediaType, Response from tests import Person, PersonFactory, PydanticDataClassPerson, VanillaDataClassPerson person = PersonFactory.build() +secret = SecretStr("secret_text") +pure_path = PurePath("/path/to/file") + + +class TestEnum(enum.Enum): + A = "alpha" + B = "beta" @pytest.mark.parametrize( @@ -20,13 +30,23 @@ [PydanticDataClassPerson(**person.dict()), PydanticDataClassPerson, MediaType.JSON], ["abcdefg", str, MediaType.TEXT], ["<div/>", str, MediaType.HTML], + [{"enum": TestEnum.A}, Dict[str, TestEnum], MediaType.JSON], + [{"secret": secret}, Dict[str, SecretStr], MediaType.JSON], + [{"pure_path": pure_path}, Dict[str, PurePath], MediaType.JSON], ], ) def test_response_serialization(content: Any, response_type: Any, media_type: MediaType) -> None: response = Response[response_type](content, media_type=media_type, status_code=HTTP_200_OK) # type: ignore[valid-type] if media_type == MediaType.JSON: value = loads(response.body) - if isinstance(value, dict): + if isinstance(value, dict) and "enum" in value: + assert content.__class__(**value)["enum"] == content["enum"].value + elif isinstance(value, dict) and "secret" in value: + assert content.__class__(**value)["secret"] == content["secret"].get_secret_value() + elif isinstance(value, dict) and "pure_path" in value: + assert content.__class__(**value)["pure_path"] == str(content["pure_path"]) + elif isinstance(value, dict): + assert content.__class__(**value) == content else: assert [content[0].__class__(**value[0])] == content
Enhancement: Add more types to the default `Response` serializer. It looks like most of the project templates we have floating around implement a custom serializer for Responses. We should consider enhancing the built in to reduce the need for this. For instance, here is the current `Response.serializer`: ```python @staticmethod def serializer(value: Any) -> Dict[str, Any]: """Serializer hook for orjson to handle pydantic models. This method can be overridden to extend json serialization. Args: value: The value to be serialized Returns: A string keyed dictionary of json compatible values """ if isinstance(value, BaseModel): return value.dict() raise TypeError # pragma: no cover ``` and here is one that's used on another project: ```python @staticmethod def serializer(value: Any) -> Dict[str, Any]: """Serializer hook for orjson to handle pydantic models. Args: value: The value to be serialized Returns: A string keyed dictionary of json compatible values """ if isinstance(value, Enum): return value.value if isinstance(value, EnumMeta): return None if isinstance(value, SecretStr): return value.get_secret_value() if isinstance(value, UUID): return str(value) return starlite.Response.serializer(value) ``` Thoughts?
@cofin - This is a good idea. Please make sure to add tests and verify that all of these are in fact needed. I would assume that `UUID` is json serializable because it implements `__str__`, and thus it wouldnt be required. I am also not sure about `Enum` in the above. I would suggest we move the default serializer out of the response class and into a `serializers` package or into file in util. It can be reused in other places Excellent. Are there others that we should add in? I would assume that all non-json serializable builtins not handled by `orjson`. You can checkout this list of types handled by `pydantic-factories` and supported by pydantic as a reference: https://github.com/Goldziher/pydantic-factories/blob/main/pydantic_factories/factory.py#L242 Another note-> please make sure to put the pydantic serializer as the first `if` clause -> it will ensure performance is pretty good.
2022-09-10T17:40:32
litestar-org/litestar
473
litestar-org__litestar-473
[ "466" ]
f7671819973f184ee949d9a7c88bdeccf3c12c25
diff --git a/starlite/connection.py b/starlite/connection.py --- a/starlite/connection.py +++ b/starlite/connection.py @@ -1,4 +1,15 @@ -from typing import TYPE_CHECKING, Any, Dict, Generic, Optional, TypeVar, Union, cast +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Generic, + Optional, + Tuple, + TypeVar, + Union, + cast, +) +from urllib.parse import parse_qsl from orjson import OPT_OMIT_MICROSECONDS, OPT_SERIALIZE_NUMPY, dumps, loads from starlette.datastructures import URL, URLPath @@ -6,10 +17,15 @@ from starlette.requests import empty_receive, empty_send from starlette.websockets import WebSocket as StarletteWebSocket from starlette.websockets import WebSocketState +from starlite_multipart import MultipartFormDataParser +from starlite_multipart import UploadFile as MultipartUploadFile +from starlite_multipart import parse_options_header +from starlite.datastructures import FormMultiDict, UploadFile +from starlite.enums import RequestEncodingType from starlite.exceptions import ImproperlyConfiguredException, InternalServerException from starlite.parsers import parse_query_params -from starlite.types import Empty +from starlite.types import Empty, EmptyType if TYPE_CHECKING: from pydantic import BaseModel @@ -184,6 +200,7 @@ class Request(URLMixin, AppMixin, SessionMixin, Generic[User, Auth], AuthMixin[U def __init__(self, scope: "Scope", receive: "Receive" = empty_receive, send: "Send" = empty_send): super().__init__(scope, receive, send) self._json: Any = Empty + self._form: Union[FormMultiDict, EmptyType] = Empty # type: ignore[assignment] @property def method(self) -> "Method": @@ -193,6 +210,16 @@ def method(self) -> "Method": """ return cast("Method", self.scope["method"]) + @property + def content_type(self) -> Tuple[str, Dict[str, str]]: + """Parses the request's 'Content-Type' header, returning the header + value and any options as a dictionary. + + Returns: + A tuple with the parsed value and a dictionary containing any options send in it. + """ + return parse_options_header(self.headers.get("Content-Type")) + async def json(self) -> Any: """Method to retrieve the json request body from the request. @@ -209,6 +236,47 @@ async def json(self) -> Any: self._json = loads(body) return self._json + async def form(self) -> FormMultiDict: # type: ignore[override] + """Method to retrieve form data from the request. If the request is + either a 'multipart/form-data' or an 'application/x-www-form- + urlencoded', this method will return a FormData instance populated with + the values sent in the request. Otherwise, an empty instance is + returned. + + Returns: + A FormData instance. + """ + if self._form is Empty: + content_type, options = self.content_type + if content_type == RequestEncodingType.MULTI_PART: + parser = MultipartFormDataParser(headers=self.headers, stream=self.stream(), max_file_size=None) + form_values = await parser() + form_values = [ + ( + k, + UploadFile( + filename=v.filename, + content_type=v.content_type, + headers=v.headers, + file=v.file, # type: ignore[arg-type] + ) + if isinstance(v, MultipartUploadFile) + else v, + ) + for k, v in form_values + ] + self._form = FormMultiDict(form_values) + + elif content_type == RequestEncodingType.URL_ENCODED: + self._form = FormMultiDict( + parse_qsl( + b"".join([chunk async for chunk in self.stream()]).decode(options.get("charset", "latin-1")) + ) + ) + else: + self._form = FormMultiDict() + return cast("FormMultiDict", self._form) + class WebSocket( # type: ignore[misc] URLMixin, AppMixin, SessionMixin, Generic[User, Auth], AuthMixin[User, Auth], QueryParamMixin, StarletteWebSocket diff --git a/starlite/datastructures.py b/starlite/datastructures.py --- a/starlite/datastructures.py +++ b/starlite/datastructures.py @@ -28,11 +28,12 @@ from pydantic_openapi_schema.v3_1_0 import Header from starlette.background import BackgroundTask as StarletteBackgroundTask from starlette.background import BackgroundTasks as StarletteBackgroundTasks +from starlette.datastructures import ImmutableMultiDict from starlette.datastructures import State as StarletteStateClass -from starlette.datastructures import UploadFile as StarletteUploadFile from starlette.responses import FileResponse, RedirectResponse from starlette.responses import Response as StarletteResponse from starlette.responses import StreamingResponse +from starlite_multipart.datastructures import UploadFile as MultipartUploadFile from typing_extensions import Literal, ParamSpec from starlite.openapi.enums import OpenAPIType @@ -341,7 +342,7 @@ def validate_value(cls, value: Any, values: Dict[str, Any]) -> Any: # pylint: d raise ValueError("value must be set if documentation_only is false") -class UploadFile(StarletteUploadFile): +class UploadFile(MultipartUploadFile): @classmethod def __modify_schema__(cls, field_schema: Dict[str, Any], field: Optional["ModelField"]) -> None: """Creates a pydantic JSON schema. @@ -355,3 +356,15 @@ def __modify_schema__(cls, field_schema: Dict[str, Any], field: Optional["ModelF """ if field: field_schema.update({"type": OpenAPIType.STRING.value, "contentMediaType": "application/octet-stream"}) + + +class FormMultiDict(ImmutableMultiDict[str, Any]): + async def close(self) -> None: + """Closes all files in the multi-dict. + + Returns: + None + """ + for _, value in self.multi_items(): + if isinstance(value, UploadFile): + await value.close() diff --git a/starlite/parsers.py b/starlite/parsers.py --- a/starlite/parsers.py +++ b/starlite/parsers.py @@ -5,7 +5,7 @@ from orjson import JSONDecodeError, loads from pydantic.fields import SHAPE_LIST, SHAPE_SINGLETON -from starlette.datastructures import UploadFile as StarletteUploadFile +from starlite_multipart.datastructures import UploadFile as MultipartUploadFile from starlite.datastructures import UploadFile from starlite.enums import RequestEncodingType @@ -14,9 +14,10 @@ from typing import Union from pydantic.fields import ModelField - from starlette.datastructures import FormData from starlette.requests import HTTPConnection + from starlite.datastructures import FormMultiDict + _true_values = {"True", "true"} _false_values = {"False", "false"} @@ -55,7 +56,7 @@ def parse_query_params(connection: "HTTPConnection") -> Dict[str, Any]: ) -def parse_form_data(media_type: "RequestEncodingType", form_data: "FormData", field: "ModelField") -> Any: +def parse_form_data(media_type: "RequestEncodingType", form_data: "FormMultiDict", field: "ModelField") -> Any: """Transforms the multidict into a regular dict, try to load json on all non-file values. @@ -63,13 +64,9 @@ def parse_form_data(media_type: "RequestEncodingType", form_data: "FormData", fi """ values_dict: Dict[str, Any] = {} for key, value in form_data.multi_items(): - if not isinstance(value, (UploadFile, StarletteUploadFile)): + if not isinstance(value, MultipartUploadFile): with suppress(JSONDecodeError): value = loads(value) - if isinstance(value, StarletteUploadFile) and not isinstance(value, UploadFile): - value = UploadFile( - filename=value.filename, file=value.file, content_type=value.content_type, headers=value.headers - ) if values_dict.get(key): if isinstance(values_dict[key], list): values_dict[key].append(value) @@ -80,6 +77,6 @@ def parse_form_data(media_type: "RequestEncodingType", form_data: "FormData", fi if media_type == RequestEncodingType.MULTI_PART: if field.shape is SHAPE_LIST: return list(values_dict.values()) - if field.shape is SHAPE_SINGLETON and field.type_ in [UploadFile, StarletteUploadFile] and values_dict: + if field.shape is SHAPE_SINGLETON and field.type_ in [UploadFile, MultipartUploadFile] and values_dict: return list(values_dict.values())[0] return values_dict
diff --git a/tests/kwargs/test_multipart_data.py b/tests/kwargs/test_multipart_data.py --- a/tests/kwargs/test_multipart_data.py +++ b/tests/kwargs/test_multipart_data.py @@ -1,11 +1,12 @@ +from os import path from typing import Any, Dict, List, Type import pytest from pydantic import BaseConfig, BaseModel from starlette.status import HTTP_201_CREATED +from starlite_multipart.datastructures import UploadFile -from starlite import Body, RequestEncodingType, post -from starlite.datastructures import UploadFile +from starlite import Body, Request, RequestEncodingType, post from starlite.testing import create_test_client from tests import Person, PersonFactory from tests.kwargs import Form @@ -20,6 +21,62 @@ class Config(BaseConfig): arbitrary_types_allowed = True +@post("/form") +async def form_handler(request: Request) -> Dict[str, Any]: + data = await request.form() + output = {} + for key, value in data.items(): + if isinstance(value, UploadFile): + content = await value.read() + output[key] = { + "filename": value.filename, + "content": content.decode(), + "content_type": value.content_type, + } + else: + output[key] = value + return output + + +@post("/form") +async def form_multi_item_handler(request: Request) -> Dict[str, Any]: + data = await request.form() + output: Dict[str, list] = {} + for key, value in data.multi_items(): + if key not in output: + output[key] = [] + if isinstance(value, UploadFile): + content = await value.read() + output[key].append( + { + "filename": value.filename, + "content": content.decode(), + "content_type": value.content_type, + } + ) + else: + output[key].append(value) + return output + + +@post("/form") +async def form_with_headers_handler(request: Request) -> Dict[str, Any]: + data = await request.form() + output = {} + for key, value in data.items(): + if isinstance(value, UploadFile): + content = await value.read() + output[key] = { + "filename": value.filename, + "content": content.decode(), + "content_type": value.content_type, + "headers": list(value.headers.items()), + } + else: + output[key] = value + return output + + @pytest.mark.parametrize("t_type", [FormData, Dict[str, UploadFile], List[UploadFile], UploadFile]) def test_request_body_multi_part(t_type: Type[Any]) -> None: body = Body(media_type=RequestEncodingType.MULTI_PART) @@ -47,7 +104,7 @@ class Config(BaseConfig): tags: List[str] profile: Person - @post(path="/") + @post(path="/form") async def test_method(data: MultiPartFormWithMixedFields = Body(media_type=RequestEncodingType.MULTI_PART)) -> None: assert await data.image.read() == b"data" assert data.tags == ["1", "2", "3"] @@ -55,8 +112,280 @@ async def test_method(data: MultiPartFormWithMixedFields = Body(media_type=Reque with create_test_client(test_method) as client: response = client.post( - "/", + "/form", files={"image": ("image.png", b"data")}, data=[("tags", "1"), ("tags", "2"), ("tags", "3"), ("profile", person.json())], ) assert response.status_code == HTTP_201_CREATED + + +def test_multipart_request_files(tmpdir: Any) -> None: + path1 = path.join(tmpdir, "test.txt") + with open(path1, "wb") as file: + file.write(b"<file content>") + + with create_test_client(form_handler) as client, open(path1, "rb") as f: + response = client.post("/form", files={"test": f}) + assert response.json() == { + "test": { + "filename": "test.txt", + "content": "<file content>", + "content_type": "", + } + } + + +def test_multipart_request_files_with_content_type(tmpdir: Any) -> None: + path1 = path.join(tmpdir, "test.txt") + with open(path1, "wb") as file: + file.write(b"<file content>") + + with create_test_client(form_handler) as client, open(path1, "rb") as f: + response = client.post("/form", files={"test": ("test.txt", f, "text/plain")}) + assert response.json() == { + "test": { + "filename": "test.txt", + "content": "<file content>", + "content_type": "text/plain", + } + } + + +def test_multipart_request_multiple_files(tmpdir: Any) -> None: + path1 = path.join(tmpdir, "test1.txt") + with open(path1, "wb") as file: + file.write(b"<file1 content>") + + path2 = path.join(tmpdir, "test2.txt") + with open(path2, "wb") as file: + file.write(b"<file2 content>") + + with create_test_client(form_handler) as client, open(path1, "rb") as f1, open(path2, "rb") as f2: + response = client.post("/form", files={"test1": f1, "test2": ("test2.txt", f2, "text/plain")}) # type: ignore + assert response.json() == { + "test1": { + "filename": "test1.txt", + "content": "<file1 content>", + "content_type": "", + }, + "test2": { + "filename": "test2.txt", + "content": "<file2 content>", + "content_type": "text/plain", + }, + } + + +def test_multipart_request_multiple_files_with_headers(tmpdir: Any) -> None: + path1 = path.join(tmpdir, "test1.txt") + with open(path1, "wb") as file: + file.write(b"<file1 content>") + + path2 = path.join(tmpdir, "test2.txt") + with open(path2, "wb") as file: + file.write(b"<file2 content>") + + with create_test_client(form_with_headers_handler) as client, open(path1, "rb") as f1, open(path2, "rb") as f2: + response = client.post( + "/form", + files=[ + ("test1", (None, f1)), + ("test2", ("test2.txt", f2, "text/plain", {"x-custom": "f2"})), + ], + ) + assert response.json() == { + "test1": "<file1 content>", + "test2": { + "filename": "test2.txt", + "content": "<file2 content>", + "content_type": "text/plain", + "headers": [ + [ + "Content-Disposition", + 'form-data; name="test2"; filename="test2.txt"', + ], + ["Content-Type", "text/plain"], + ["x-custom", "f2"], + ], + }, + } + + +def test_multi_items(tmpdir: Any) -> None: + path1 = path.join(tmpdir, "test1.txt") + with open(path1, "wb") as file: + file.write(b"<file1 content>") + + path2 = path.join(tmpdir, "test2.txt") + with open(path2, "wb") as file: + file.write(b"<file2 content>") + + with create_test_client(form_multi_item_handler) as client, open(path1, "rb") as f1, open(path2, "rb") as f2: + response = client.post( + "/form", + data=[("test1", "abc")], + files=[("test1", f1), ("test1", ("test2.txt", f2, "text/plain"))], + ) + assert response.json() == { + "test1": [ + "abc", + { + "filename": "test1.txt", + "content": "<file1 content>", + "content_type": "", + }, + { + "filename": "test2.txt", + "content": "<file2 content>", + "content_type": "text/plain", + }, + ] + } + + +def test_multipart_request_mixed_files_and_data() -> None: + with create_test_client(form_handler) as client: + response = client.post( + "/form", + data=( + # data + b"--a7f7ac8d4e2e437c877bb7b8d7cc549c\r\n" + b'Content-Disposition: form-data; name="field0"\r\n\r\n' + b"value0\r\n" + # file + b"--a7f7ac8d4e2e437c877bb7b8d7cc549c\r\n" + b'Content-Disposition: form-data; name="file"; filename="file.txt"\r\n' + b"Content-Type: text/plain\r\n\r\n" + b"<file content>\r\n" + # data + b"--a7f7ac8d4e2e437c877bb7b8d7cc549c\r\n" + b'Content-Disposition: form-data; name="field1"\r\n\r\n' + b"value1\r\n" + b"--a7f7ac8d4e2e437c877bb7b8d7cc549c--\r\n" + ), + headers={"Content-Type": ("multipart/form-data; boundary=a7f7ac8d4e2e437c877bb7b8d7cc549c")}, + ) + assert response.json() == { + "file": { + "filename": "file.txt", + "content": "<file content>", + "content_type": "text/plain", + }, + "field0": "value0", + "field1": "value1", + } + + +def test_multipart_request_with_charset_for_filename() -> None: + with create_test_client(form_handler) as client: + response = client.post( + "/form", + data=( + # file + b"--a7f7ac8d4e2e437c877bb7b8d7cc549c\r\n" + b'Content-Disposition: form-data; name="file"; filename="\xe6\x96\x87\xe6\x9b\xb8.txt"\r\n' # noqa: E501 + b"Content-Type: text/plain\r\n\r\n" + b"<file content>\r\n" + b"--a7f7ac8d4e2e437c877bb7b8d7cc549c--\r\n" + ), + headers={"Content-Type": ("multipart/form-data; charset=utf-8; boundary=a7f7ac8d4e2e437c877bb7b8d7cc549c")}, + ) + assert response.json() == { + "file": { + "filename": "文書.txt", + "content": "<file content>", + "content_type": "text/plain", + } + } + + +def test_multipart_request_without_charset_for_filename() -> None: + with create_test_client(form_handler) as client: + response = client.post( + "/form", + data=( + # file + b"--a7f7ac8d4e2e437c877bb7b8d7cc549c\r\n" + b'Content-Disposition: form-data; name="file"; filename="\xe7\x94\xbb\xe5\x83\x8f.jpg"\r\n' # noqa: E501 + b"Content-Type: image/jpeg\r\n\r\n" + b"<file content>\r\n" + b"--a7f7ac8d4e2e437c877bb7b8d7cc549c--\r\n" + ), + headers={"Content-Type": ("multipart/form-data; boundary=a7f7ac8d4e2e437c877bb7b8d7cc549c")}, + ) + assert response.json() == { + "file": { + "filename": "画像.jpg", + "content": "<file content>", + "content_type": "image/jpeg", + } + } + + +def test_multipart_request_with_encoded_value() -> None: + with create_test_client(form_handler) as client: + response = client.post( + "/form", + data=( + b"--20b303e711c4ab8c443184ac833ab00f\r\n" + b"Content-Disposition: form-data; " + b'name="value"\r\n\r\n' + b"Transf\xc3\xa9rer\r\n" + b"--20b303e711c4ab8c443184ac833ab00f--\r\n" + ), + headers={"Content-Type": ("multipart/form-data; charset=utf-8; boundary=20b303e711c4ab8c443184ac833ab00f")}, + ) + assert response.json() == {"value": "Transférer"} + + +def test_urlencoded_request_data() -> None: + with create_test_client(form_handler) as client: + response = client.post("/form", data={"some": "data"}) + assert response.json() == {"some": "data"} + + +def test_no_request_data() -> None: + with create_test_client(form_handler) as client: + response = client.post("/form") + assert response.json() == {} + + +def test_urlencoded_percent_encoding() -> None: + with create_test_client(form_handler) as client: + response = client.post("/form", data={"some": "da ta"}) + assert response.json() == {"some": "da ta"} + + +def test_urlencoded_percent_encoding_keys() -> None: + with create_test_client(form_handler) as client: + response = client.post("/form", data={"so me": "data"}) + assert response.json() == {"so me": "data"} + + +def test_postman_multipart_form_data() -> None: + postman_body = b'----------------------------850116600781883365617864\r\nContent-Disposition: form-data; name="attributes"; filename="test-attribute_5.tsv"\r\nContent-Type: text/tab-separated-values\r\n\r\n"Campaign ID"\t"Plate Set ID"\t"No"\n\r\n----------------------------850116600781883365617864\r\nContent-Disposition: form-data; name="fasta"; filename="test-sequence_correct_5.fasta"\r\nContent-Type: application/octet-stream\r\n\r\n>P23G01_IgG1-1411:H:Q10C3:1/1:NID18\r\nCAGGTATTGAA\r\n\r\n----------------------------850116600781883365617864--\r\n' # noqa: E501 + postman_headers = { + "Content-Type": "multipart/form-data; boundary=--------------------------850116600781883365617864", # noqa: E501 + "user-agent": "PostmanRuntime/7.26.0", + "accept": "*/*", + "cache-control": "no-cache", + "host": "10.0.5.13:80", + "accept-encoding": "gzip, deflate, br", + "connection": "keep-alive", + "content-length": "2455", + } + + with create_test_client(form_handler) as client: + response = client.post("/form", data=postman_body, headers=postman_headers) + assert response.json() == { + "attributes": { + "filename": "test-attribute_5.tsv", + "content": '"Campaign ID"\t"Plate Set ID"\t"No"\n', + "content_type": "text/tab-separated-values", + }, + "fasta": { + "filename": "test-sequence_correct_5.fasta", + "content": ">P23G01_IgG1-1411:H:Q10C3:1/1:NID18\r\nCAGGTATTGAA\r\n", + "content_type": "application/octet-stream", + }, + }
Enhancement: replace python-multipart with a faster and more stable multipart parser python-multipart extremely slow, not maintaining (0.0.5 version released at 12 Oct 2018) and have problems with text files (xml, json, csv etc ) need to swap it to baize or some else https://github.com/h0rn3t/starlette-opt/commit/96a7a08b54a24650ad331c4f812659609e7a1494
Are there any benchmarks to support this? 25mb xml in form-data (python-multipart) = 1-2 min parsing (some problems internal problem in parsing algorithm ) 25mb xml in form-data (baize) patched starlette = 6 seconds BTW im not first who ask to swap this old python-multipart library, also the code of that lib not so good @peterschutt @cofin @infohash -- what do you think? I looked at Baize and the multipart implementation does look good. I am concerned though adding this dependency into the project - its not modular and we are going to get some annoying import issues. I opened an issue in their github -> https://github.com/abersheeran/baize/issues/47 An alternative would be to fork either baize or the python multipart and create our own smaller implementation. @h0rn3t - how interested are you in contributing to this? Plenty of prior art out there to guide us in implementing ourselves. Flask and Quart both use [werkzeug.sansio.multipart](https://github.com/pallets/werkzeug/blob/main/src/werkzeug/sansio/multipart.py) and the baize implementation seems to be just a copy of that. Falcon, sanic and django all roll their own implementations as well. Aight, I'll check this out. Might be an interesting case > 25mb xml in form-data (python-multipart) = 1-2 min parsing (some problems internal problem in parsing algorithm ) 25mb xml in form-data (baize) patched starlette = 6 seconds I didn't even think I could be so fast...thanks mypyc > Plenty of prior art out there to guide us in implementing ourselves. > > Flask and Quart both use [werkzeug.sansio.multipart](https://github.com/pallets/werkzeug/blob/main/src/werkzeug/sansio/multipart.py) and the baize implementation seems to be just a copy of that. Falcon, sanic and django all roll their own implementations as well. Yes, it's better to build the parser in starlite, which means some targeted optimizations can be made. The multipart format is an old, stable construct that requires little maintenance once the code is written. I met with the problem of long file uploads too. And it was connected to the old python-multipart library. I was surprised that such an old library without proper support for async is still used in fastapi (using many dependencies from Starlette) I started work on a library to handle this. I will be using Werkzeug as a basis. > I met with the problem of long file uploads too. And it was connected to the old python-multipart library. I was surprised that such an old library without proper support for async is still used in fastapi (using many dependencies from Starlette) https://github.com/encode/starlette/pull/1514#issuecomment-1041362805 @h0rn3t -- I created a package, adapting werkzeug and using your PR to starlette as a basis. See: https://github.com/starlite-api/starlite-multipart Would you like to get involved?
2022-09-10T19:35:52
litestar-org/litestar
481
litestar-org__litestar-481
[ "479" ]
07202e9b9ca1e819d0ca4a9b90fec6e007e7adde
diff --git a/starlite/handlers/http.py b/starlite/handlers/http.py --- a/starlite/handlers/http.py +++ b/starlite/handlers/http.py @@ -187,10 +187,11 @@ def _create_data_handler( async def handler(data: Any, plugins: List["PluginProtocol"], **kwargs: Any) -> StarletteResponse: data = await _normalize_response_data(data=data, plugins=plugins) normalized_cookies = _normalize_cookies(cookies, []) + normalized_headers = _normalize_headers(headers) response = response_class( background=background, content=data, - headers=headers, + headers=normalized_headers, media_type=media_type, status_code=status_code, )
diff --git a/tests/response/test_response_headers.py b/tests/response/test_response_headers.py --- a/tests/response/test_response_headers.py +++ b/tests/response/test_response_headers.py @@ -1,7 +1,11 @@ +from typing import Dict + import pytest from pydantic import ValidationError +from starlette.status import HTTP_201_CREATED -from starlite import Controller, HttpMethod, ResponseHeader, Router, Starlite, get +from starlite import Controller, HttpMethod, ResponseHeader, Router, Starlite, get, post +from starlite.testing import create_test_client def test_response_headers() -> None: @@ -53,3 +57,18 @@ def test_response_headers_validation() -> None: ResponseHeader(documentation_only=True) with pytest.raises(ValidationError): ResponseHeader() + + +def test_response_headers_rendering() -> None: + @post( + path="/test", + tags=["search"], + response_headers={"test-header": ResponseHeader(value="test value", description="test")}, + ) + def my_handler(data: Dict[str, str]) -> Dict[str, str]: + return data + + with create_test_client(my_handler) as client: + response = client.post("/test", json={"hello": "world"}) + assert response.status_code == HTTP_201_CREATED + assert response.headers.get("test-header") == "test value"
ResponseHeader throws `object has no attribute 'encode'` error **Describe the bug** When I try to set headers: ``` python @post(tags=["search"],response_headers = { "testheader": ResponseHeader(value="test value",description="test") }) ``` I get: ```python AttributeError("'ResponseHeader' object has no attribute 'encode'") ``` **To Reproduce** [this repo](https://github.com/denizkenan/starlite-hello-world) has mentioned bug
2022-09-14T19:34:49
litestar-org/litestar
483
litestar-org__litestar-483
[ "482" ]
df29e1dc49b1cdd713d2aa76a024b1ddee444879
diff --git a/starlite/datastructures.py b/starlite/datastructures.py --- a/starlite/datastructures.py +++ b/starlite/datastructures.py @@ -36,6 +36,7 @@ from starlite_multipart.datastructures import UploadFile as MultipartUploadFile from typing_extensions import Literal, ParamSpec +from starlite.enums import MediaType from starlite.openapi.enums import OpenAPIType P = ParamSpec("P") @@ -44,7 +45,6 @@ from pydantic.fields import ModelField from starlite.app import Starlite - from starlite.enums import MediaType from starlite.response import TemplateResponse @@ -156,6 +156,8 @@ class Config(BaseConfig): """A string/string dictionary of response headers. Header keys are insensitive. Defaults to None.""" cookies: List[Cookie] = [] """A list of Cookie instances to be set under the response 'Set-Cookie' header. Defaults to None.""" + media_type: Optional[Union[MediaType, str]] = None + """If defined, overrides the media type configured in the route decorator""" @abstractmethod def to_response( diff --git a/starlite/handlers/http.py b/starlite/handlers/http.py --- a/starlite/handlers/http.py +++ b/starlite/handlers/http.py @@ -138,7 +138,9 @@ def _create_response_container_handler( async def handler(data: ResponseContainer, app: "Starlite", **kwargs: Any) -> StarletteResponse: normalized_headers = {**_normalize_headers(headers), **data.headers} normalized_cookies = _normalize_cookies(data.cookies, cookies) - response = data.to_response(app=app, headers=normalized_headers, status_code=status_code, media_type=media_type) + response = data.to_response( + app=app, headers=normalized_headers, status_code=status_code, media_type=data.media_type or media_type + ) for cookie in normalized_cookies: response.set_cookie(**cookie) return await after_request(response) if after_request else response # type: ignore @@ -498,7 +500,6 @@ def resolve_response_handler( response_class = self.resolve_response_class() headers = self.resolve_response_headers() cookies = self.resolve_response_cookies() - if is_class_and_subclass(self.signature.return_annotation, ResponseContainer): # type: ignore[misc] handler = _create_response_container_handler( after_request=after_request,
diff --git a/tests/response/test_serialization.py b/tests/response/test_serialization.py --- a/tests/response/test_serialization.py +++ b/tests/response/test_serialization.py @@ -15,7 +15,7 @@ pure_path = PurePath("/path/to/file") -class TestEnum(enum.Enum): +class _TestEnum(enum.Enum): A = "alpha" B = "beta" @@ -30,13 +30,15 @@ class TestEnum(enum.Enum): [PydanticDataClassPerson(**person.dict()), PydanticDataClassPerson, MediaType.JSON], ["abcdefg", str, MediaType.TEXT], ["<div/>", str, MediaType.HTML], - [{"enum": TestEnum.A}, Dict[str, TestEnum], MediaType.JSON], + [{"enum": _TestEnum.A}, Dict[str, _TestEnum], MediaType.JSON], [{"secret": secret}, Dict[str, SecretStr], MediaType.JSON], [{"pure_path": pure_path}, Dict[str, PurePath], MediaType.JSON], ], ) def test_response_serialization(content: Any, response_type: Any, media_type: MediaType) -> None: - response = Response[response_type](content, media_type=media_type, status_code=HTTP_200_OK) # type: ignore[valid-type] + response = Response[response_type]( # type: ignore[valid-type] + content, media_type=media_type, status_code=HTTP_200_OK + ) if media_type == MediaType.JSON: value = loads(response.body) if isinstance(value, dict) and "enum" in value:
File response should accept byte stream and `media_type` as an alternative to file path. **What's the feature you'd like to ask for.** As of v1.18.1: Starlite's [File](https://starlite-api.github.io/starlite/usage/5-responses/7-file-responses/) response only supports returning existing files. ``` python return File( path=Path(Path(__file__).resolve().parent, "report").with_suffix(".pdf"), filename="repost.pdf", ) ``` However, it should be able to support returning files directly from byte streams such as BytesIO. This would enable apps that can't use filesystem (eg. Google App Engine) to return files without much workaround. In addition to that, File response should _optionally_ accept `media_type` as it is quite useful to set it dynamically depending on the file content. Therefore, we should be able to return file by passing data and media type to File class like: ``` python ... data = io.BytesIO() ... do something data.. return File( content=data, filename=filename, media_type='application/vnd.ms-excel', headers={f'Content-Disposition': f'attachment; filename={filename}'}, ) ``` ❤️ Thank you very much :)
Would a streaming response be what you are looking for here? ```python """Minimal Starlite application.""" import io from starlite import Starlite, get from starlite.datastructures import Stream from starlite.enums import MediaType @get("/", media_type=MediaType.TEXT) def hello_world() -> Stream: byte_stream = io.BytesIO(b"some byte string\n") """Hi.""" return Stream(iterator=byte_stream) app = Starlite(route_handlers=[hello_world]) ``` ``` $ curl localhost:8000/ some byte string ``` Nope, I solely meant using stream as source for file download. Sure but when it boils down to it, `FileResponse` is streaming chunks of bytes just like `StreamingResponse` does: From [FileResponse](https://github.com/encode/starlette/blob/bc61505faef15b673bf4bf65db4927daa354d6b8/starlette/responses.py#L349-L360): ```python async with await anyio.open_file(self.path, mode="rb") as file: more_body = True while more_body: chunk = await file.read(self.chunk_size) more_body = len(chunk) == self.chunk_size await send( { "type": "http.response.body", "body": chunk, "more_body": more_body, } ) ``` And from [StreamingResponse](https://github.com/encode/starlette/blob/bc61505faef15b673bf4bf65db4927daa354d6b8/starlette/responses.py#L258-L263): ```python async for chunk in self.body_iterator: if not isinstance(chunk, bytes): chunk = chunk.encode(self.charset) await send({"type": "http.response.body", "body": chunk, "more_body": True}) await send({"type": "http.response.body", "body": b"", "more_body": False}) ``` Say we added a `content` attribute to `File` we'd have to produce a `StreamResponse` from it anyway, unless we wrote the stream to a temporary file before passing it to `FileResponse`, which I dont think is the way to go. Also setting headers and media type on the responses is possible if you want to drop down a level and call the `to_response()` method: ```python """Minimal Starlite application.""" import io from starlette.responses import StreamingResponse from starlite import Starlite, get, Request from starlite.datastructures import Stream from starlite.enums import MediaType @get("/", media_type=MediaType.TEXT) def hello_world(request: Request) -> StreamingResponse: byte_stream = io.BytesIO(b"some byte string\n\n") """Hi.""" return Stream(iterator=byte_stream).to_response( headers={f"Content-Disposition": f"attachment; filename=my-file"}, media_type="application/vnd.ms-excel", status_code=200, app=request.app, ) app = Starlite(route_handlers=[hello_world]) ``` Issue with that though is that we lose the openapi docs when we return the starlette response directly. ![image](https://user-images.githubusercontent.com/20659309/190387228-4e4ef88c-a7ee-46dc-8f12-21645c5abeb3.png) Thanks a lot for the tip! I managed to get it working as well. (https://github.com/denizkenan/starlite-hello-world) `curl localhost:8000/greetings` I fully agree with you. It is just better dx to handle this purely within starlite using File response. I don't think it is super edge case for us to use lower level APIs. So if we made `media_type` configurable on `ResponseContainer` so you could do this: ```python """Minimal Starlite application.""" import io from starlite import Starlite, get from starlite.datastructures import Stream from starlite.enums import MediaType @get("/", media_type=MediaType.TEXT) def starlite() -> Stream: byte_stream = io.BytesIO(b"some byte string\n\n") """Hi.""" return Stream( iterator=byte_stream, headers={f"Content-Disposition": f"attachment; filename=my-file"}, media_type="application/vnd.ms-excel", ) app = Starlite(route_handlers=[starlite]) ``` Would that be the solution you are looking for?
2022-09-15T12:05:25
litestar-org/litestar
549
litestar-org__litestar-549
[ "548" ]
e7ca42cb7facbfa54cbf5a2bd07af9b128dcbfe7
diff --git a/starlite/plugins/sql_alchemy/plugin.py b/starlite/plugins/sql_alchemy/plugin.py --- a/starlite/plugins/sql_alchemy/plugin.py +++ b/starlite/plugins/sql_alchemy/plugin.py @@ -30,7 +30,8 @@ from sqlalchemy import inspect from sqlalchemy import types as sqlalchemy_type from sqlalchemy.dialects import mssql, mysql, oracle, postgresql, sqlite - from sqlalchemy.orm import DeclarativeMeta, Mapper + from sqlalchemy.exc import NoInspectionAvailable + from sqlalchemy.orm import DeclarativeMeta, InstanceState, Mapper from sqlalchemy.sql.type_api import TypeEngine except ImportError as e: raise MissingDependencyException("sqlalchemy is not installed") from e @@ -88,7 +89,11 @@ def is_plugin_supported_type(value: Any) -> "TypeGuard[DeclarativeMeta]": Returns: A boolean typeguard. """ - return isinstance(value, DeclarativeMeta) or isinstance(value.__class__, DeclarativeMeta) + try: + inspected = inspect(value) + except NoInspectionAvailable: + return False + return isinstance(inspected, (Mapper, InstanceState)) @staticmethod def handle_string_type(column_type: Union[sqlalchemy_type.String, sqlalchemy_type._Binary]) -> "Type": @@ -329,13 +334,18 @@ def parse_model(model_class: DeclarativeMeta) -> Mapper: model_class: An SQLAlchemy declarative class. Returns: - An SQLAlchemy inspection 'Mapper'. + A SQLAlchemy `Mapper`. """ - if not isinstance(model_class, DeclarativeMeta): - raise ImproperlyConfiguredException( - "Unsupported 'model_class' kwarg: only subclasses of the SQLAlchemy `DeclarativeMeta` are supported" - ) - return inspect(model_class) + try: + inspected = inspect(model_class) + except NoInspectionAvailable: + pass + else: + if isinstance(inspected, Mapper): + return inspected + raise ImproperlyConfiguredException( + "Unsupported 'model_class' kwarg: only subclasses of the SQLAlchemy `DeclarativeMeta` are supported" + ) def to_pydantic_model_class(self, model_class: Type[DeclarativeMeta], **kwargs: Any) -> "Type[BaseModel]": """Generates a pydantic model for a given SQLAlchemy declarative table
Bug: SQLAlchemyPlugin type detection not compatible with SQLAlchemy 2.0 For example: ```python-console >>> from starlite import DTOFactory >>> from starlite.plugins.sql_alchemy import SQLAlchemyPlugin >>> dto_factory = DTOFactory(plugins=[SQLAlchemyPlugin()]) >>> UpdateAuthorDTO = dto_factory("UpdateAuthorDTO", Author, exclude=["created", "updated"]) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.10/site-packages/starlite/dto.py", line 216, in __call__ fields, plugin = self._get_fields_from_source(source) File "/usr/local/lib/python3.10/site-packages/starlite/dto.py", line 242, in _get_fields_from_source raise ImproperlyConfiguredException( starlite.exceptions.http_exceptions.ImproperlyConfiguredException: 500: No supported plugin found for value <class 'app.domain.authors.Author'> - cannot create value >>> type(Author) <class 'sqlalchemy.orm.decl_api.DeclarativeAttributeIntercept'> ```
2022-10-06T10:48:00
litestar-org/litestar
556
litestar-org__litestar-556
[ "555" ]
7abf1aa66c9d6eed35fa47e2ac067f52e35fda25
diff --git a/starlite/plugins/sql_alchemy/config.py b/starlite/plugins/sql_alchemy/config.py --- a/starlite/plugins/sql_alchemy/config.py +++ b/starlite/plugins/sql_alchemy/config.py @@ -12,7 +12,7 @@ ) from orjson import OPT_SERIALIZE_NUMPY, dumps, loads -from pydantic import BaseConfig, BaseModel, validator +from pydantic import BaseConfig, BaseModel, root_validator, validator from typing_extensions import Literal from starlite.config.logging import BaseLoggingConfig, LoggingConfig @@ -147,7 +147,7 @@ class SQLAlchemyConfig(BaseModel): class Config(BaseConfig): arbitrary_types_allowed = True - connection_string: str + connection_string: Optional[str] = None """Database connection string in one of the formats supported by SQLAlchemy. Notes: @@ -236,6 +236,30 @@ def validate_before_send_handler( # pylint: disable=no-self-argument """ return AsyncCallable(value) # type: ignore[arg-type] + @root_validator + def check_connection_string_or_engine_instance( # pylint: disable=no-self-argument + cls, values: Dict[str, Any] + ) -> Dict[str, Any]: + """Either `connection_string` or `engine_instance` must be specified, + and not both. + + Args: + values: Field values, after validation. + + Returns: + Field values. + """ + connection_string = values.get("connection_string") + engine_instance = values.get("engine_instance") + + if connection_string is None and engine_instance is None: + raise ValueError("One of 'connection_string' or 'engine_instance' must be provided.") + + if connection_string is not None and engine_instance is not None: + raise ValueError("Only one of 'connection_string' or 'engine_instance' can be provided.") + + return values + @property def engine_config_dict(self) -> Dict[str, Any]: """ @@ -261,7 +285,9 @@ def engine(self) -> Union["Engine", "FutureEngine", "AsyncEngine"]: create_engine_callable = ( self.create_async_engine_callable if self.use_async_engine else self.create_engine_callable ) - self.engine_instance = create_engine_callable(self.connection_string, **self.engine_config_dict) + self.engine_instance = create_engine_callable( + self.connection_string, **self.engine_config_dict # type:ignore[arg-type] + ) return cast("Union[Engine, FutureEngine, AsyncEngine]", self.engine_instance) @property
diff --git a/tests/plugins/sql_alchemy_plugin/test_sql_alchemy_config.py b/tests/plugins/sql_alchemy_plugin/test_sql_alchemy_config.py --- a/tests/plugins/sql_alchemy_plugin/test_sql_alchemy_config.py +++ b/tests/plugins/sql_alchemy_plugin/test_sql_alchemy_config.py @@ -1,6 +1,8 @@ from typing import Any, Optional import pytest +from pydantic import ValidationError +from sqlalchemy import create_engine from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm import Session from starlette.status import HTTP_200_OK @@ -99,3 +101,18 @@ def test_logging_config(engine_logger: Optional[str], pool_logger: Optional[str] def test_default_serializer_returns_string() -> None: assert serializer({"hello": "world"}) == '{"hello":"world"}' + + +def test_config_connection_string_or_engine_instance_validation() -> None: + with pytest.raises(ValidationError): + SQLAlchemyConfig(connection_string=None, engine_instance=None) + + connection_string = "sqlite:///" + engine = create_engine(connection_string) + + with pytest.raises(ValidationError): + SQLAlchemyConfig(connection_string=connection_string, engine_instance=engine) + + # these should be OK + SQLAlchemyConfig(engine_instance=engine) + SQLAlchemyConfig(connection_string=connection_string) diff --git a/tests/plugins/sql_alchemy_plugin/test_sqlalchemy_plugin.py b/tests/plugins/sql_alchemy_plugin/test_sqlalchemy_plugin.py new file mode 100644 --- /dev/null +++ b/tests/plugins/sql_alchemy_plugin/test_sqlalchemy_plugin.py @@ -0,0 +1,67 @@ +from typing import Any + +import pytest +from sqlalchemy import Column, Integer +from sqlalchemy.orm import Mapper, as_declarative, declarative_base + +from starlite.exceptions import ImproperlyConfiguredException +from starlite.plugins.sql_alchemy import SQLAlchemyPlugin + +DeclBase = declarative_base() + + +@as_declarative() +class AsDeclBase: + ... + + +class FromAsDeclarative(AsDeclBase): + __tablename__ = "whatever" + id = Column(Integer, primary_key=True) + + +class FromDeclBase(DeclBase): # type:ignore[misc,valid-type] + __tablename__ = "whatever" + id = Column(Integer, primary_key=True) + + +class Plain: + ... + + [email protected]( + "item,result", + [ + (FromAsDeclarative, True), + (FromAsDeclarative(), True), + (FromDeclBase, True), + (FromDeclBase(), True), + (Plain, False), + (Plain(), False), + (None, False), + ("str", False), + ], +) +def test_is_plugin_supported_type(item: Any, result: bool) -> None: + assert SQLAlchemyPlugin.is_plugin_supported_type(item) is result + + [email protected]( + "item,should_raise", + [ + (FromAsDeclarative, False), + (FromAsDeclarative(), True), + (FromDeclBase, False), + (FromDeclBase(), True), + (Plain, True), + (Plain(), True), + (None, True), + ("str", True), + ], +) +def test_parse_model(item: Any, should_raise: bool) -> None: + if should_raise: + with pytest.raises(ImproperlyConfiguredException): + SQLAlchemyPlugin.parse_model(item) + else: + assert isinstance(SQLAlchemyPlugin.parse_model(item), Mapper) diff --git a/tests/test_testing.py b/tests/test_testing.py --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -202,6 +202,6 @@ def test_handler(state: State, request: Request) -> None: app = Starlite(route_handlers=[test_handler], on_startup=[start_up_handler], middleware=[session_config.middleware]) with TestClient(app=app, session_config=session_config if enable_session else None) as client: - cookies = client.create_session_cookies(session_data=session_data) - client.get("/test", cookies=cookies) + client.cookies = client.create_session_cookies(session_data=session_data) + client.get("/test") assert app.state.value == 1
Testing: DeprecationWarning: Setting per-request cookies ``` tests/test_testing.py::test_test_client[True-session_data0] tests/test_testing.py::test_test_client[False-session_data1] /home/peter/.cache/pypoetry/virtualenvs/starlite-CEGnKvDD-py3.10/lib/python3.10/site-packages/httpx/_client.py:800: DeprecationWarning: Setting per-request cookies=<...> is being deprecated, because the expected behaviour on cookie persistence is ambiguous. Set cookies directly on the client instance instead. warnings.warn(message, DeprecationWarning) -- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html ``` HTTPX are deprecating setting cookies per request. ```python @pytest.mark.parametrize("enable_session, session_data", [(True, {"user": "test-user"}), (False, {})]) def test_test_client(enable_session: bool, session_data: Dict[str, str]) -> None: ... with TestClient(app=app, session_config=session_config if enable_session else None) as client: cookies = client.create_session_cookies(session_data=session_data) client.get("/test", cookies=cookies) assert app.state.value == 1 ``` Easy fix to silence the warning: ```python @pytest.mark.parametrize("enable_session, session_data", [(True, {"user": "test-user"}), (False, {})]) def test_test_client(enable_session: bool, session_data: Dict[str, str]) -> None: ... with TestClient(app=app, session_config=session_config if enable_session else None) as client: client.cookies = client.create_session_cookies(session_data=session_data) client.get("/test") assert app.state.value == 1 ``` Perhaps we should consider adding `TestClient.set_session_cookies()` method as well.
2022-10-07T01:58:15
litestar-org/litestar
561
litestar-org__litestar-561
[ "558" ]
717ce5e3da33ff8b28c0caeb23c0b47d9bd91774
diff --git a/starlite/plugins/sql_alchemy/config.py b/starlite/plugins/sql_alchemy/config.py --- a/starlite/plugins/sql_alchemy/config.py +++ b/starlite/plugins/sql_alchemy/config.py @@ -20,6 +20,8 @@ from starlite.types import BeforeMessageSendHookHandler from starlite.utils import AsyncCallable, default_serializer +from .types import SessionMakerInstanceProtocol, SessionMakerTypeProtocol + try: from sqlalchemy import create_engine from sqlalchemy.engine import Engine @@ -200,7 +202,7 @@ class Config(BaseConfig): Configuration options for the 'sessionmaker'. The configuration options are documented in the SQLAlchemy documentation. """ - session_maker_class: Type[sessionmaker] = sessionmaker + session_maker_class: Type[SessionMakerTypeProtocol] = sessionmaker """ Sessionmaker class to use. """ @@ -208,7 +210,7 @@ class Config(BaseConfig): """ Key under which to store the SQLAlchemy 'sessionmaker' in the application [State][starlite.datastructures.State] instance. """ - session_maker_instance: Optional[sessionmaker] = None + session_maker_instance: Optional[SessionMakerInstanceProtocol] = None """ Optional sessionmaker to use. If set, the plugin will use the provided instance rather than instantiate a sessionmaker. """ diff --git a/starlite/plugins/sql_alchemy/plugin.py b/starlite/plugins/sql_alchemy/plugin.py --- a/starlite/plugins/sql_alchemy/plugin.py +++ b/starlite/plugins/sql_alchemy/plugin.py @@ -25,6 +25,8 @@ ) from starlite.plugins.base import PluginProtocol +from .types import SQLAlchemyBinaryType + try: from sqlalchemy import inspect from sqlalchemy import types as sqlalchemy_type @@ -95,7 +97,7 @@ def is_plugin_supported_type(value: Any) -> "TypeGuard[DeclarativeMeta]": return isinstance(inspected, (Mapper, InstanceState)) @staticmethod - def handle_string_type(column_type: Union[sqlalchemy_type.String, sqlalchemy_type._Binary]) -> "Type": + def handle_string_type(column_type: Union[sqlalchemy_type.String, SQLAlchemyBinaryType]) -> "Type": """Handles the SQLAlchemy String types, including Blob and Binary types. @@ -138,7 +140,7 @@ def handle_list_type(self, column_type: sqlalchemy_type.ARRAY) -> Any: dimensions -= 1 return list_type - def handle_tuple_type(self, column_type: sqlalchemy_type.TupleType) -> Any: + def handle_tuple_type(self, column_type: sqlalchemy_type.TupleType) -> Any: # type:ignore[name-defined] """Handles the SQLAlchemy Tuple type. Args: @@ -160,10 +162,10 @@ def handle_enum(column_type: Union[sqlalchemy_type.Enum, mysql.ENUM, postgresql. Returns: An appropriate enum type """ - return column_type.enum_class + return column_type.enum_class # type:ignore[union-attr] @property - def providers_map(self) -> Dict["Type[TypeEngine]", Callable[[Union[TypeEngine, "Type[TypeEngine]"]], Any]]: + def providers_map(self) -> Dict[Type[TypeEngine], Callable[[Union[TypeEngine, Type[TypeEngine]]], Any]]: """A map of SQLAlchemy column types to provider functions. This method is separated to allow for easy overriding in @@ -209,7 +211,7 @@ def providers_map(self) -> Dict["Type[TypeEngine]", Callable[[Union[TypeEngine, sqlalchemy_type.TIMESTAMP: lambda x: datetime, sqlalchemy_type.Text: self.handle_string_type, sqlalchemy_type.Time: lambda x: time, - sqlalchemy_type.TupleType: self.handle_tuple_type, + sqlalchemy_type.TupleType: self.handle_tuple_type, # type:ignore[attr-defined] sqlalchemy_type.Unicode: self.handle_string_type, sqlalchemy_type.UnicodeText: self.handle_string_type, sqlalchemy_type.VARBINARY: self.handle_string_type, @@ -325,7 +327,7 @@ def get_pydantic_type(self, column_type: Any) -> Any: return type(column_type) @staticmethod - def parse_model(model_class: DeclarativeMeta) -> Mapper: + def parse_model(model_class: Type[DeclarativeMeta]) -> Mapper: """Validates that the passed in model_class is an SQLAlchemy declarative model, and returns a Mapper of it. diff --git a/starlite/plugins/sql_alchemy/types.py b/starlite/plugins/sql_alchemy/types.py new file mode 100644 --- /dev/null +++ b/starlite/plugins/sql_alchemy/types.py @@ -0,0 +1,35 @@ +from typing import TYPE_CHECKING, Any, Dict, Optional, Type, Union + +from typing_extensions import Protocol, runtime_checkable + +if TYPE_CHECKING: + from sqlalchemy.engine import Connection, Engine + from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession + from sqlalchemy.orm import Session + from sqlalchemy.types import BINARY, VARBINARY, LargeBinary + + +SQLAlchemyBinaryType = Union["BINARY", "VARBINARY", "LargeBinary"] + + +@runtime_checkable +class SessionMakerTypeProtocol(Protocol): + def __init__( + self, + bind: "Optional[Union[AsyncEngine, Engine, Connection]]", + class_: "Union[Type[AsyncSession], Type[Session]]", + autoflush: bool, + expire_on_commit: bool, + info: Dict[Any, Any], + **kwargs: Any, + ) -> None: + ... + + def __call__(self) -> "Union[Session, AsyncSession]": + ... + + +@runtime_checkable +class SessionMakerInstanceProtocol(Protocol): + def __call__(self) -> "Union[Session, AsyncSession]": + ...
diff --git a/tests/dto_factory/test_dto_factory_model_conversion.py b/tests/dto_factory/test_dto_factory_model_conversion.py --- a/tests/dto_factory/test_dto_factory_model_conversion.py +++ b/tests/dto_factory/test_dto_factory_model_conversion.py @@ -64,7 +64,7 @@ def test_conversion_from_model_instance( pets=None, ) else: - model_instance = cast("Type[Pet]", model)( # type: ignore[call-arg] + model_instance = cast("Type[Pet]", model)( id=1, species=Species.MONKEY, name="Mike", diff --git a/tests/plugins/sql_alchemy_plugin/__init__.py b/tests/plugins/sql_alchemy_plugin/__init__.py --- a/tests/plugins/sql_alchemy_plugin/__init__.py +++ b/tests/plugins/sql_alchemy_plugin/__init__.py @@ -1,3 +1,5 @@ +from typing import List + from sqlalchemy import Column, Enum, Float, ForeignKey, Integer, String, Table from sqlalchemy.orm import as_declarative, declared_attr, relationship @@ -11,18 +13,18 @@ class SQLAlchemyBase: # Generate the table name from the class name @declared_attr def __tablename__(cls) -> str: - return cls.__name__.lower() # type:ignore[no-any-return,attr-defined] + return cls.__name__.lower() association_table = Table( "association", - SQLAlchemyBase.metadata, # type:ignore[attr-defined] + SQLAlchemyBase.metadata, Column("pet_id", ForeignKey("pet.id")), Column("user_id", ForeignKey("user.id")), ) friendship_table = Table( "friendships", - SQLAlchemyBase.metadata, # type:ignore[attr-defined] + SQLAlchemyBase.metadata, Column("friend_a_id", Integer, ForeignKey("user.id"), primary_key=True), Column("friend_b_id", Integer, ForeignKey("user.id"), primary_key=True), ) @@ -34,7 +36,7 @@ class Pet(SQLAlchemyBase): name = Column(String) age = Column(Float) owner_id = Column(Integer, ForeignKey("user.id")) - owner = relationship("User", back_populates="pets", uselist=False) + owner: "User" = relationship("User", back_populates="pets", uselist=False) class Company(SQLAlchemyBase): @@ -46,8 +48,8 @@ class Company(SQLAlchemyBase): class User(SQLAlchemyBase): id = Column(Integer, primary_key=True) name = Column(String, default="moishe") - pets = relationship("Pet", back_populates="owner", uselist=True) - friends = relationship( + pets: List[Pet] = relationship("Pet", back_populates="owner", uselist=True) + friends: List["User"] = relationship( "User", secondary=friendship_table, primaryjoin=id == friendship_table.c.friend_a_id, @@ -55,4 +57,4 @@ class User(SQLAlchemyBase): uselist=True, ) company_id = Column(Integer, ForeignKey("company.id")) - company = relationship("Company") + company: Company = relationship("Company") diff --git a/tests/plugins/sql_alchemy_plugin/test_sql_alchemy_config.py b/tests/plugins/sql_alchemy_plugin/test_sql_alchemy_config.py --- a/tests/plugins/sql_alchemy_plugin/test_sql_alchemy_config.py +++ b/tests/plugins/sql_alchemy_plugin/test_sql_alchemy_config.py @@ -4,7 +4,7 @@ from pydantic import ValidationError from sqlalchemy import create_engine from sqlalchemy.ext.asyncio import AsyncSession -from sqlalchemy.orm import Session +from sqlalchemy.orm import Session, sessionmaker from starlette.status import HTTP_200_OK from starlite import LoggingConfig, Starlite, get @@ -116,3 +116,18 @@ def test_config_connection_string_or_engine_instance_validation() -> None: # these should be OK SQLAlchemyConfig(engine_instance=engine) SQLAlchemyConfig(connection_string=connection_string) + + +def test_config_session_maker_class_protocol() -> None: + """Tests that pydantic allows the type, but also relies on mypy checking + that `sessionmaker` conforms to the protocol.""" + SQLAlchemyConfig(connection_string="sqlite:///", session_maker_class=sessionmaker) + + +def test_config_session_maker_instance_protocol() -> None: + """Tests that pydantic allows the type, but also relies on mypy checking + that `sessionmaker` conforms to the protocol.""" + SQLAlchemyConfig(connection_string="sqlite:///", session_maker_instance=sessionmaker()) + # instance can be any callable that returns a session type instance + SQLAlchemyConfig(connection_string="sqlite:///", session_maker_instance=Session) + SQLAlchemyConfig(connection_string="sqlite:///", session_maker_instance=AsyncSession) diff --git a/tests/plugins/sql_alchemy_plugin/test_sql_alchemy_plugin_integration.py b/tests/plugins/sql_alchemy_plugin/test_sql_alchemy_plugin_integration.py --- a/tests/plugins/sql_alchemy_plugin/test_sql_alchemy_plugin_integration.py +++ b/tests/plugins/sql_alchemy_plugin/test_sql_alchemy_plugin_integration.py @@ -12,7 +12,7 @@ from tests.plugins.sql_alchemy_plugin import Company companies = [ - Company(id=i, name=create_random_string(min_length=5, max_length=20), worth=create_random_float(minimum=1)) # type: ignore[call-arg] + Company(id=i, name=create_random_string(min_length=5, max_length=20), worth=create_random_float(minimum=1)) for i in range(3) ] diff --git a/tests/plugins/sql_alchemy_plugin/test_sql_alchemy_relationships.py b/tests/plugins/sql_alchemy_plugin/test_sql_alchemy_relationships.py --- a/tests/plugins/sql_alchemy_plugin/test_sql_alchemy_relationships.py +++ b/tests/plugins/sql_alchemy_plugin/test_sql_alchemy_relationships.py @@ -8,7 +8,7 @@ def test_relationship() -> None: - result = SQLAlchemyPlugin().to_pydantic_model_class(model_class=User) + result = SQLAlchemyPlugin().to_pydantic_model_class(model_class=User) # type:ignore[arg-type] assert issubclass(result, BaseModel) result.update_forward_refs() fields = result.__fields__ diff --git a/tests/plugins/sql_alchemy_plugin/test_sql_alchemy_table_types.py b/tests/plugins/sql_alchemy_plugin/test_sql_alchemy_table_types.py --- a/tests/plugins/sql_alchemy_plugin/test_sql_alchemy_table_types.py +++ b/tests/plugins/sql_alchemy_plugin/test_sql_alchemy_table_types.py @@ -221,7 +221,7 @@ class MyClass(BaseModel): def test_provider_validation() -> None: - class MyStrColumn(sqlalchemy.String): # type:ignore[misc] + class MyStrColumn(sqlalchemy.String): pass class ModelWithCustomColumn(SQLAlchemyBase): diff --git a/tests/plugins/sql_alchemy_plugin/test_sqlalchemy_plugin.py b/tests/plugins/sql_alchemy_plugin/test_sqlalchemy_plugin.py --- a/tests/plugins/sql_alchemy_plugin/test_sqlalchemy_plugin.py +++ b/tests/plugins/sql_alchemy_plugin/test_sqlalchemy_plugin.py @@ -20,7 +20,7 @@ class FromAsDeclarative(AsDeclBase): id = Column(Integer, primary_key=True) -class FromDeclBase(DeclBase): # type:ignore[misc,valid-type] +class FromDeclBase(DeclBase): __tablename__ = "whatever" id = Column(Integer, primary_key=True)
Bug: SQLAlchemy Plugin won't accept `async_sessionmaker` for `session_maker_instance` ``` app_1 | Traceback (most recent call last): app_1 | File "/usr/local/bin/alembic", line 8, in <module> app_1 | sys.exit(main()) app_1 | File "/usr/local/lib/python3.10/site-packages/alembic/config.py", line 590, in main app_1 | CommandLine(prog=prog).main(argv=argv) app_1 | File "/usr/local/lib/python3.10/site-packages/alembic/config.py", line 584, in main app_1 | self.run_cmd(cfg, options) app_1 | File "/usr/local/lib/python3.10/site-packages/alembic/config.py", line 561, in run_cmd app_1 | fn( app_1 | File "/usr/local/lib/python3.10/site-packages/alembic/command.py", line 322, in upgrade app_1 | script.run_env() app_1 | File "/usr/local/lib/python3.10/site-packages/alembic/script/base.py", line 569, in run_env app_1 | util.load_python_file(self.dir, "env.py") app_1 | File "/usr/local/lib/python3.10/site-packages/alembic/util/pyfiles.py", line 94, in load_python_file app_1 | module = load_module_py(module_id, path) app_1 | File "/usr/local/lib/python3.10/site-packages/alembic/util/pyfiles.py", line 110, in load_module_py app_1 | spec.loader.exec_module(module) # type: ignore app_1 | File "<frozen importlib._bootstrap_external>", line 883, in exec_module app_1 | File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed app_1 | File "/app/alembic/env.py", line 9, in <module> app_1 | from app.lib import orm, settings app_1 | File "/app/./app/lib/__init__.py", line 3, in <module> app_1 | from . import ( app_1 | File "/app/./app/lib/sqlalchemy_plugin.py", line 111, in <module> app_1 | config = SQLAlchemyConfig( app_1 | File "pydantic/main.py", line 342, in pydantic.main.BaseModel.__init__ app_1 | pydantic.error_wrappers.ValidationError: 1 validation error for SQLAlchemyConfig app_1 | session_maker_instance app_1 | instance of sessionmaker expected (type=type_error.arbitrary_type; expected_arbitrary_type=sessionmaker) ``` `async_sessionmaker` doesn't exist in 1.x and unfortunately isn't a subclass of `sessionmaker`. I'm think of making these protocols instead - for `session_maker_class` we care that we receive a type that has the `sessionmaker.__init__()` interface, and creates a callable that returns a session. For `session_maker_instance` we only care that we receive a callable that returns either `Session` or `AsyncSession` - so pretty sure I can express all of that with protocols, without needing to strongly type to `sessionmaker`.
2022-10-07T14:03:23
litestar-org/litestar
569
litestar-org__litestar-569
[ "567" ]
51e029cb934b6b78373f9894b85c9529a0d0b136
diff --git a/starlite/app.py b/starlite/app.py --- a/starlite/app.py +++ b/starlite/app.py @@ -101,8 +101,8 @@ class HandlerIndex(TypedDict): """Full route paths to the route handler.""" handler: "RouteHandlerType" """Route handler instance.""" - qualname: str - """Qualname of the handler""" + identifier: str + """Unique identifier of the handler. Either equal to the 'name' attribute or the __str__ value of the handler.""" class HandlerNode(TypedDict): @@ -467,12 +467,11 @@ def handler() -> None: if not handler: return None - qualname = self._get_handler_qualname(handler) - - routes = self._route_mapping[qualname] + identifier = handler.name or str(handler) + routes = self._route_mapping[identifier] paths = sorted(unique([route.path for route in routes])) - return HandlerIndex(handler=handler, paths=paths, qualname=qualname) + return HandlerIndex(handler=handler, paths=paths, identifier=identifier) def route_reverse(self, name: str, **path_parameters: Any) -> Optional[str]: """Receives a route handler name, path parameter values and returns an @@ -483,7 +482,7 @@ def route_reverse(self, name: str, **path_parameters: Any) -> Optional[str]: from starlite import Starlite, get - @get("/group/{group_id:int}/user/{user_id:int}", name="get_memebership_details") + @get("/group/{group_id:int}/user/{user_id:int}", name="get_membership_details") def get_membership_details(group_id: int, user_id: int) -> None: pass @@ -512,7 +511,7 @@ def get_membership_details(group_id: int, user_id: int) -> None: output: List[str] = [] routes = sorted( - self._route_mapping[handler_index["qualname"]], key=lambda r: len(r.path_parameters), reverse=True + self._route_mapping[handler_index["identifier"]], key=lambda r: len(r.path_parameters), reverse=True ) passed_parameters = set(path_parameters.keys()) @@ -614,7 +613,8 @@ def _add_node_to_route_map(self, route: BaseRoute) -> RouteMapNode: self._configure_route_map_node(route, current_node) return current_node - def _get_route_handlers(self, route: BaseRoute) -> List["RouteHandlerType"]: + @staticmethod + def _get_route_handlers(route: BaseRoute) -> List["RouteHandlerType"]: """Retrieve handler(s) as a list for given route.""" route_handlers: List["RouteHandlerType"] = [] if isinstance(route, (WebSocketRoute, ASGIRoute)): @@ -624,14 +624,6 @@ def _get_route_handlers(self, route: BaseRoute) -> List["RouteHandlerType"]: return route_handlers - def _get_handler_qualname(self, handler: "RouteHandlerType") -> str: - """Retrieves __qualname__ for passed route handler.""" - handler_fn = cast("AnyCallable", handler.fn) - if hasattr(handler_fn, "__qualname__"): - return handler_fn.__qualname__ - - return type(handler_fn).__qualname__ - def _store_handler_to_route_mapping(self, route: BaseRoute) -> None: """Stores the mapping of route handlers to routes and to route handler names. @@ -645,18 +637,15 @@ def _store_handler_to_route_mapping(self, route: BaseRoute) -> None: route_handlers = self._get_route_handlers(route) for handler in route_handlers: - qualname = self._get_handler_qualname(handler) - self._route_mapping[qualname].append(route) - - name = handler.name or self._get_handler_qualname(handler) - - if ( - name in self._route_handler_index - and self._get_handler_qualname(self._route_handler_index[name]) != qualname + if handler.name in self._route_handler_index and str(self._route_handler_index[handler.name]) != str( + handler ): - raise ImproperlyConfiguredException(f"route handler names must be unique - {name} is not unique.") - - self._route_handler_index[name] = handler + raise ImproperlyConfiguredException( + f"route handler names must be unique - {handler.name} is not unique." + ) + identifier = handler.name or str(handler) + self._route_mapping[identifier].append(route) + self._route_handler_index[identifier] = handler def _configure_route_map_node(self, route: BaseRoute, node: RouteMapNode) -> None: """Set required attributes and route handlers on route_map tree diff --git a/starlite/handlers/base.py b/starlite/handlers/base.py --- a/starlite/handlers/base.py +++ b/starlite/handlers/base.py @@ -210,3 +210,13 @@ def _validate_handler_function(self) -> None: return annotations.""" if not self.fn: raise ImproperlyConfiguredException("Cannot call _validate_handler_function without first setting self.fn") + + def __str__(self) -> str: + """ + Returns: + A unique identifier for the route handler + """ + target = cast("Any", self.fn) + if not hasattr(target, "__qualname__"): + target = type(target) + return f"{target.__module__}.{target.__qualname__}" diff --git a/starlite/utils/exception.py b/starlite/utils/exception.py --- a/starlite/utils/exception.py +++ b/starlite/utils/exception.py @@ -29,7 +29,7 @@ def get_exception_handler( Args: exception_handlers: Mapping of status codes and exception types to handlers. - exc: Exception Instance to be resolved to a handler. + exc: Exception Instance to be resolved to a handler. Returns: Optional exception handler callable.
diff --git a/tests/kwargs/test_multipart_data.py b/tests/kwargs/test_multipart_data.py --- a/tests/kwargs/test_multipart_data.py +++ b/tests/kwargs/test_multipart_data.py @@ -238,7 +238,7 @@ def test_multipart_request_mixed_files_and_data() -> None: b"value1\r\n" b"--a7f7ac8d4e2e437c877bb7b8d7cc549c--\r\n" ), - headers={"Content-Type": ("multipart/form-data; boundary=a7f7ac8d4e2e437c877bb7b8d7cc549c")}, + headers={"Content-Type": "multipart/form-data; boundary=a7f7ac8d4e2e437c877bb7b8d7cc549c"}, ) assert response.json() == { "file": { @@ -263,7 +263,7 @@ def test_multipart_request_with_charset_for_filename() -> None: b"<file content>\r\n" b"--a7f7ac8d4e2e437c877bb7b8d7cc549c--\r\n" ), - headers={"Content-Type": ("multipart/form-data; charset=utf-8; boundary=a7f7ac8d4e2e437c877bb7b8d7cc549c")}, + headers={"Content-Type": "multipart/form-data; charset=utf-8; boundary=a7f7ac8d4e2e437c877bb7b8d7cc549c"}, ) assert response.json() == { "file": { @@ -286,7 +286,7 @@ def test_multipart_request_without_charset_for_filename() -> None: b"<file content>\r\n" b"--a7f7ac8d4e2e437c877bb7b8d7cc549c--\r\n" ), - headers={"Content-Type": ("multipart/form-data; boundary=a7f7ac8d4e2e437c877bb7b8d7cc549c")}, + headers={"Content-Type": "multipart/form-data; boundary=a7f7ac8d4e2e437c877bb7b8d7cc549c"}, ) assert response.json() == { "file": { @@ -308,7 +308,7 @@ def test_multipart_request_with_encoded_value() -> None: b"Transf\xc3\xa9rer\r\n" b"--20b303e711c4ab8c443184ac833ab00f--\r\n" ), - headers={"Content-Type": ("multipart/form-data; charset=utf-8; boundary=20b303e711c4ab8c443184ac833ab00f")}, + headers={"Content-Type": "multipart/form-data; charset=utf-8; boundary=20b303e711c4ab8c443184ac833ab00f"}, ) assert response.json() == {"value": "Transférer"} diff --git a/tests/routing/test_route_indexing.py b/tests/routing/test_route_indexing.py --- a/tests/routing/test_route_indexing.py +++ b/tests/routing/test_route_indexing.py @@ -73,20 +73,18 @@ def handler(self) -> None: router = Router("router/", route_handlers=[handler, named_handler, MyController]) app = Starlite(route_handlers=[router]) - handler_index = app.get_handler_index_by_name(handler.fn.__qualname__) # type: ignore + handler_index = app.get_handler_index_by_name(handler.name or str(handler)) assert handler_index assert handler_index["paths"] == ["/router/handler"] assert handler_index["handler"] == handler - assert handler_index["qualname"] == handler.fn.__qualname__ # type: ignore + assert handler_index["identifier"] == handler.name or str(handler) - handler_index = app.get_handler_index_by_name(MyController.handler.fn.__qualname__) # type: ignore + handler_index = app.get_handler_index_by_name(MyController.handler.name or str(MyController.handler)) assert handler_index assert handler_index["paths"] == ["/router/test"] - # we can not do an assertion on handlers in Controller subclasses - assert handler_index["qualname"] == MyController.handler.fn.__qualname__ # type: ignore + assert handler_index["identifier"] == MyController.handler.name or str(MyController.handler) - # test that passing route name overrides default name completely - handler_index = app.get_handler_index_by_name(named_handler.fn.__qualname__) # type: ignore + handler_index = app.get_handler_index_by_name(named_handler) # type: ignore assert handler_index is None diff --git a/tests/template/test_template.py b/tests/template/test_template.py --- a/tests/template/test_template.py +++ b/tests/template/test_template.py @@ -44,11 +44,11 @@ def test_template_response_receives_request_in_context(template_dir: Path) -> No Path(template_dir / "abc.html").write_text("") @get(path="/") - def hanler() -> Template: + def handler() -> Template: return Template(name="abc.html", context={}) with patch("starlite.response.TemplateResponse") as template_response_mock, create_test_client( - route_handlers=[hanler], + route_handlers=[handler], template_config=TemplateConfig( directory=template_dir, engine=JinjaTemplateEngine, @@ -64,15 +64,15 @@ def hanler() -> Template: assert isinstance(request, Request) -def test_request_can_not_be_overriden_in_context(template_dir: Path) -> None: +def test_request_can_not_be_overridden_in_context(template_dir: Path) -> None: Path(template_dir / "abc.html").write_text("") @get(path="/") - def hanler() -> Template: + def handler() -> Template: return Template(name="abc.html", context={"request": 123}) with patch("starlite.response.TemplateResponse") as template_response_mock, create_test_client( - route_handlers=[hanler], + route_handlers=[handler], template_config=TemplateConfig( directory=template_dir, engine=JinjaTemplateEngine, diff --git a/tests/test_router_registration.py b/tests/test_router_registration.py --- a/tests/test_router_registration.py +++ b/tests/test_router_registration.py @@ -142,23 +142,23 @@ def _handler() -> None: app = Starlite(route_handlers=[first_router, second_router, handler]) - assert app.route_handler_method_view[handler.fn.__qualname__] == ["/root"] # type: ignore - assert app.route_handler_method_view[MyController.get_method.fn.__qualname__] == [ # type: ignore + assert app.route_handler_method_view[str(handler)] == ["/root"] + assert app.route_handler_method_view[str(MyController.get_method)] == [ "/first/test", "/second/test", ] - assert app.route_handler_method_view[MyController.ws.fn.__qualname__] == [ # type: ignore + assert app.route_handler_method_view[str(MyController.ws)] == [ "/first/test/socket", "/second/test/socket", ] - assert app.route_handler_method_view[put_handler.fn.__qualname__] == [ # type: ignore + assert app.route_handler_method_view[str(put_handler)] == [ "/first/send", "/first/modify", "/second/send", "/second/modify", ] - assert app.route_handler_method_view[put_handler.fn.__qualname__] == [ # type: ignore + assert app.route_handler_method_view[str(post_handler)] == [ "/first/send", "/first/modify", "/second/send",
Default name in handler index is not unique **Describe the bug** Default name for route handlers might be not unique. [Here](https://github.com/starlite-api/starlite/pull/541#discussion_r987565608) we decided to use `handler.fn.__qualname__` as default name in handler index but today I learned the hard way that `__qualname__` is not unique if your route handlers are functions with the same name located in different files. Sorry, I didn't check python docs carefully to make sure that picked named would be unique. Easy repro ``` /tmp/test > cat a.py def create(): pass /tmp/test > cat b.py def create(): pass /tmp/test > python Python 3.10.7 (main, Sep 6 2022, 21:22:27) [GCC 12.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from a import create as create_a >>> from b import create as create_b >>> create_a.__qualname__ 'create' >>> create_b.__qualname__ 'create' >>> ``` Django uses `func.__module__ + "." + func.__qualname__' for similar purposes as can be see [here](https://github.com/django/django/blob/974942a75039ba43e618f6a5ff95e08b5d5176fd/django/contrib/admindocs/utils.py#L22) I tried it https://github.com/starlite-api/starlite/compare/main...jtraub:starlite:fix_default_name_in_index and it works fine for my case. Maybe "internal" method `app._get_handler_qualname` should be moved to utils so the user can import and use it - at the moment I ha to duplicate the code in my app
yup
2022-10-08T20:01:24
litestar-org/litestar
588
litestar-org__litestar-588
[ "585" ]
a06e157ee55af8a18f33328031b4db23c9f0b25f
diff --git a/starlite/handlers/http.py b/starlite/handlers/http.py --- a/starlite/handlers/http.py +++ b/starlite/handlers/http.py @@ -7,7 +7,6 @@ Callable, Dict, List, - NoReturn, Optional, Type, Union, @@ -574,11 +573,11 @@ def _validate_handler_function(self) -> None: if return_annotation is Signature.empty: raise ImproperlyConfiguredException( "A return value of a route handler function should be type annotated." - "If your function doesn't return a value or returns None, annotate it as returning 'NoReturn' or 'None' respectively." + "If your function doesn't return a value, annotate it as returning 'None'." ) if ( self.status_code < 200 or self.status_code in {HTTP_204_NO_CONTENT, HTTP_304_NOT_MODIFIED} - ) and return_annotation not in {NoReturn, None}: + ) and return_annotation is not None: raise ImproperlyConfiguredException( "A status code 204, 304 or in the range below 200 does not support a response body." "If the function should return a value, change the route handler status code to an appropriate value.", diff --git a/starlite/response.py b/starlite/response.py --- a/starlite/response.py +++ b/starlite/response.py @@ -1,14 +1,4 @@ -from typing import ( - TYPE_CHECKING, - Any, - Dict, - Generic, - NoReturn, - Optional, - TypeVar, - Union, - cast, -) +from typing import TYPE_CHECKING, Any, Dict, Generic, Optional, TypeVar, Union, cast import yaml from orjson import OPT_INDENT_2, OPT_OMIT_MICROSECONDS, OPT_SERIALIZE_NUMPY, dumps @@ -83,10 +73,8 @@ def render(self, content: Any) -> bytes: An encoded bytes string """ try: - if ( - content is None - or content is NoReturn - and (self.status_code < 100 or self.status_code in {HTTP_204_NO_CONTENT, HTTP_304_NOT_MODIFIED}) + if content is None and ( + self.status_code < 100 or self.status_code in {HTTP_204_NO_CONTENT, HTTP_304_NOT_MODIFIED} ): return b"" if self.media_type == MediaType.JSON:
diff --git a/tests/handlers/http/test_delete.py b/tests/handlers/http/test_delete.py --- a/tests/handlers/http/test_delete.py +++ b/tests/handlers/http/test_delete.py @@ -1,15 +1,10 @@ -from typing import Any, NoReturn - -import pytest - from starlite import delete from starlite.testing import create_test_client [email protected]("return_annotation", (None, NoReturn)) -def test_handler_return_none_and_204_status_response_empty(return_annotation: Any) -> None: +def test_handler_return_none_and_204_status_response_empty() -> None: @delete(path="/") - async def route() -> return_annotation: # type: ignore[valid-type] + async def route() -> None: return None with create_test_client(route_handlers=[route]) as client:
Fix: remove `NoReturn` as a supported return value for `delete`. ### Discussed in https://github.com/starlite-api/starlite/discussions/583 <div type='discussions-op-text'> <sup>Originally posted by **Goldziher** October 13, 2022</sup> We currenty support `NoReturn` as a valid return value for the `delete` method, which cannot support returning a value with uvicorn (which freaks out if it does return a value, while hypercorn and other servers do not). We should decide how we want to proceed given that in the official PEP for this type it is determined that it should be used only for special functions that never return a value, like endless loops or functions that raise exceptions: https://peps.python.org/pep-0484/#the-noreturn-type. </div>
2022-10-13T16:21:39
litestar-org/litestar
594
litestar-org__litestar-594
[ "593" ]
f97b5b210738fb8b9230faed4f44b7aa146e44ae
diff --git a/starlite/config/logging.py b/starlite/config/logging.py --- a/starlite/config/logging.py +++ b/starlite/config/logging.py @@ -132,7 +132,7 @@ class LoggingConfig(BaseLoggingConfig, BaseModel): } """A dict in which each key is a logger name and each value is a dict describing how to configure the corresponding Logger instance.""" root: Dict[str, Union[Dict[str, Any], List[Any], str]] = { - "handlers": ["queue_listener", "console"], + "handlers": ["queue_listener"], "level": "INFO", } """This will be the configuration for the root logger. Processing of the configuration will be as for any logger, diff --git a/starlite/logging/picologging.py b/starlite/logging/picologging.py --- a/starlite/logging/picologging.py +++ b/starlite/logging/picologging.py @@ -1,5 +1,4 @@ import atexit -from io import StringIO from logging import StreamHandler from queue import Queue from typing import Any, List, Optional @@ -28,7 +27,7 @@ def __init__(self, handlers: Optional[List[Any]] = None) -> None: if handlers: handlers = resolve_handlers(handlers) else: - handlers = [StreamHandler(StringIO())] + handlers = [StreamHandler()] self.listener = QueueListener(self.queue, *handlers) self.listener.start() diff --git a/starlite/logging/standard.py b/starlite/logging/standard.py --- a/starlite/logging/standard.py +++ b/starlite/logging/standard.py @@ -1,5 +1,4 @@ import atexit -from io import StringIO from logging import StreamHandler from logging.handlers import QueueHandler, QueueListener from queue import Queue @@ -20,7 +19,7 @@ def __init__(self, handlers: Optional[List[Any]] = None) -> None: if handlers: handlers = resolve_handlers(handlers) else: - handlers = [StreamHandler(StringIO())] + handlers = [StreamHandler()] self.listener = QueueListener(self.queue, *handlers) self.listener.start()
Bug: logging queue listener writing to in-memory stream The handler for the `queue_listener` handler is created as `StreamHandler(StringIO())`. Explicitly passing the stream to the the handler means that the output is no longer logged to stderr.
2022-10-14T14:06:06
litestar-org/litestar
595
litestar-org__litestar-595
[ "592" ]
f97b5b210738fb8b9230faed4f44b7aa146e44ae
diff --git a/starlite/signature.py b/starlite/signature.py --- a/starlite/signature.py +++ b/starlite/signature.py @@ -348,8 +348,10 @@ def create_signature_model(self) -> Type[SignatureModel]: self.collect_dependency_names(parameter) self.set_field_default(parameter) if self.should_skip_parameter_validation(parameter): - # pydantic has issues with none-pydantic classes that receive generics - self.field_definitions[parameter.name] = (Any, ...) + if is_dependency_field(parameter.default): + self.field_definitions[parameter.name] = (Any, parameter.default.default) + else: + self.field_definitions[parameter.name] = (Any, ...) continue if ModelFactory.is_constrained_field(parameter.default): self.field_definitions[parameter.name] = (parameter.default, ...) diff --git a/starlite/utils/dependency.py b/starlite/utils/dependency.py --- a/starlite/utils/dependency.py +++ b/starlite/utils/dependency.py @@ -1,11 +1,14 @@ -from typing import Any +from typing import TYPE_CHECKING, Any from pydantic.fields import FieldInfo from starlite.constants import EXTRA_KEY_IS_DEPENDENCY, EXTRA_KEY_SKIP_VALIDATION +if TYPE_CHECKING: + from typing_extensions import TypeGuard -def is_dependency_field(val: Any) -> bool: + +def is_dependency_field(val: Any) -> "TypeGuard[FieldInfo]": """Determine if a value is a `FieldInfo` instance created via the `Dependency()` function. @@ -29,4 +32,4 @@ def should_skip_dependency_validation(val: Any) -> bool: `True` if `val` is `FieldInfo` created by [`Dependency()`][starlite.params.Dependency] function and `skip_validation=True` is set. """ - return is_dependency_field(val) and val.extra.get(EXTRA_KEY_SKIP_VALIDATION) + return is_dependency_field(val) and bool(val.extra.get(EXTRA_KEY_SKIP_VALIDATION))
diff --git a/tests/test_dependency.py b/tests/test_dependency.py --- a/tests/test_dependency.py +++ b/tests/test_dependency.py @@ -94,3 +94,14 @@ def skipped(value: int = Dependency(skip_validation=True)) -> Dict[str, int]: skipped_resp = client.get("/skipped") assert skipped_resp.status_code == HTTP_200_OK assert skipped_resp.json() == {"value": "str"} + + +def test_dependency_skip_validation_with_default_value() -> None: + @get("/skipped") + def skipped(value: int = Dependency(default=1, skip_validation=True)) -> Dict[str, int]: + return {"value": value} + + with create_test_client(route_handlers=[skipped]) as client: + skipped_resp = client.get("/skipped") + assert skipped_resp.status_code == HTTP_200_OK + assert skipped_resp.json() == {"value": 1}
Bug: Dependency function passes `...` when both `default` and `skip_validation` are specified ```python @get("/") def hello_world(a: int = Dependency(default=1, skip_validation=True)) -> dict[str, Any]: """Route Handler that outputs hello world.""" print(f"{a = }, {type(a) = }") # a = Ellipsis, type(a) = <class 'ellipsis'> return {"hello": "world"} ``` default value injected into handler function is `Ellipsis`, should be `1`.
2022-10-14T14:25:14
litestar-org/litestar
610
litestar-org__litestar-610
[ "609" ]
7f51736e83fe5e7d4e72b5aa6fc1f95051d13dc0
diff --git a/starlite/logging/picologging.py b/starlite/logging/picologging.py --- a/starlite/logging/picologging.py +++ b/starlite/logging/picologging.py @@ -1,5 +1,4 @@ import atexit -from logging import StreamHandler from queue import Queue from typing import Any, List, Optional @@ -7,6 +6,7 @@ from starlite.logging.utils import resolve_handlers try: + from picologging import StreamHandler from picologging.handlers import QueueHandler, QueueListener except ImportError as e: raise MissingDependencyException("picologging is not installed") from e
Bug: Picologging not behaving correctly **Describe the bug** i reported an earlier issue to @peterschutt about logging configuration not visible in the console output. that was fixed in https://github.com/starlite-api/starlite/pull/594 i now wanted to test this out with picologging but it seems to override the LoggingConfig settings. **To Reproduce** checkout https://github.com/starlite-api/starlite-pg-redis-docker and add picologging to the application. then you see the behaviour i describe here. nothing else changes so only add picologging. **Additional context** you can see the behaviour already at starting the project with docker-compose up. without picologging in project: app_1 | Starting Starlite App... app_1 | INFO: Will watch for changes in these directories: ['/app'] app_1 | INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit) app_1 | INFO: Started reloader process [10] using WatchFiles app_1 | INFO: Started server process [12] app_1 | INFO: Waiting for application startup. app_1 | 2022-10-16 18:38:14,888 loglevel=INFO logger=uvicorn.error serve() L75 Started server process [12] app_1 | 2022-10-16 18:38:14,888 loglevel=INFO logger=uvicorn.error startup() L47 Waiting for application startup. app_1 | INFO: Application startup complete. app_1 | 2022-10-16 18:38:14,908 loglevel=INFO logger=uvicorn.error startup() L61 Application startup complete. with picologging in project: app_1 | Starting Starlite App... app_1 | INFO: Will watch for changes in these directories: ['/app'] app_1 | INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit) app_1 | INFO: Started reloader process [10] using WatchFiles app_1 | INFO: Started server process [12] app_1 | INFO: Waiting for application startup. app_1 | INFO: Application startup complete. i tried looking at the documentation of picologging https://microsoft.github.io/picologging/handlers.html section Queue Listener but it seems to be correct. at this point im lacking knowledge in the logging department to troubleshoot this deeper. Kind regards, Niels
2022-10-16T19:23:33
litestar-org/litestar
620
litestar-org__litestar-620
[ "619" ]
8064f3291b4c2a295f10aa0318ed2217580d565a
diff --git a/starlite/router.py b/starlite/router.py --- a/starlite/router.py +++ b/starlite/router.py @@ -1,5 +1,5 @@ import collections -from typing import TYPE_CHECKING, Dict, ItemsView, List, Optional, Type, Union, cast +from typing import TYPE_CHECKING, Dict, ItemsView, List, Optional, Union, cast from pydantic import validate_arguments from pydantic_openapi_schema.v3_1_0 import SecurityRequirement @@ -19,7 +19,7 @@ AfterResponseHookHandler, BeforeRequestHookHandler, ControllerRouterHandler, - ExceptionHandler, + ExceptionHandlersMap, Guard, Middleware, ParametersMap, @@ -70,7 +70,7 @@ def __init__( after_response: Optional[AfterResponseHookHandler] = None, before_request: Optional[BeforeRequestHookHandler] = None, dependencies: Optional[Dict[str, Provide]] = None, - exception_handlers: Optional[Dict[Union[int, Type[Exception]], ExceptionHandler]] = None, + exception_handlers: Optional[ExceptionHandlersMap] = None, guards: Optional[List[Guard]] = None, middleware: Optional[List[Middleware]] = None, parameters: Optional[ParametersMap] = None, diff --git a/starlite/types/callable_types.py b/starlite/types/callable_types.py --- a/starlite/types/callable_types.py +++ b/starlite/types/callable_types.py @@ -1,4 +1,4 @@ -from typing import TYPE_CHECKING, Any, Awaitable, Callable, Union +from typing import TYPE_CHECKING, Any, Awaitable, Callable, TypeVar, Union from .asgi_types import Message, Scope from .helpers import SyncOrAsyncUnion @@ -24,6 +24,8 @@ WebsocketRouteHandler = Any Logger = Any +_ExceptionT = TypeVar("_ExceptionT", bound=Exception) + AfterExceptionHookHandler = Callable[[Exception, Scope, State], SyncOrAsyncUnion[None]] AfterRequestHookHandler = Union[ Callable[[StarletteResponse], SyncOrAsyncUnion[StarletteResponse]], Callable[[Response], SyncOrAsyncUnion[Response]] @@ -36,7 +38,7 @@ ] BeforeRequestHookHandler = Callable[[Request], Union[Any, Awaitable[Any]]] CacheKeyBuilder = Callable[[Request], str] -ExceptionHandler = Callable[[Request, Exception], StarletteResponse] +ExceptionHandler = Callable[[Request, _ExceptionT], StarletteResponse] Guard = Union[ Callable[[Request, HTTPRouteHandler], SyncOrAsyncUnion[None]], Callable[[WebSocket, WebsocketRouteHandler], SyncOrAsyncUnion[None]], diff --git a/starlite/utils/exception.py b/starlite/utils/exception.py --- a/starlite/utils/exception.py +++ b/starlite/utils/exception.py @@ -1,5 +1,5 @@ from inspect import getmro -from typing import TYPE_CHECKING, Any, Dict, List, Optional, Type, Union, cast +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union, cast from pydantic import BaseModel from starlette.exceptions import HTTPException as StarletteHTTPException @@ -10,12 +10,12 @@ from starlite.response import Response if TYPE_CHECKING: - from starlite.types import ExceptionHandler + from typing import Type + from starlite.types import ExceptionHandler, ExceptionHandlersMap -def get_exception_handler( - exception_handlers: Dict[Union[int, Type[Exception]], "ExceptionHandler"], exc: Exception -) -> Optional["ExceptionHandler"]: + +def get_exception_handler(exception_handlers: "ExceptionHandlersMap", exc: Exception) -> Optional["ExceptionHandler"]: """Given a dictionary that maps exceptions and status codes to handler functions, and an exception, returns the appropriate handler if existing.
Typing: ExceptionHandler Exception type invariant ```py class ExceptionSubclass(Exception): ... def fn(req: Request, exc: ExceptionSubclass) -> Response: ... e: ExceptionHandler = fn ``` Mypy error: ``` error: Incompatible types in assignment (expression has type "Callable[[Request[Any, Any], ExceptionSubclass], starlite.response.Response[Any]]", variable has type "Callable[[Request[Any, Any], Exception], Union[starlite.response.Response[Any], starlette.responses.Response]]") [assignment] ```
2022-10-19T10:51:41
litestar-org/litestar
629
litestar-org__litestar-629
[ "628", "628" ]
d11d0fb90e2d43467090ddfdf4d0ae3ca14e3bb9
diff --git a/starlite/middleware/session.py b/starlite/middleware/session.py --- a/starlite/middleware/session.py +++ b/starlite/middleware/session.py @@ -1,5 +1,6 @@ import binascii import contextlib +import re import time from base64 import b64decode, b64encode from os import urandom @@ -138,6 +139,7 @@ def __init__( self.app = app self.config = config self.aesgcm = AESGCM(config.secret.get_secret_value()) + self.cookie_re = re.compile(rf"{self.config.key}(?:-\d+)?") def dump_data(self, data: Any, scope: Optional["Scope"] = None) -> List[bytes]: """Given orjson serializable data, including pydantic models and numpy @@ -256,7 +258,7 @@ async def __call__(self, scope: "Scope", receive: "Receive", send: "Send") -> No if scope["type"] in self.config.scopes: scope.setdefault("session", {}) connection = ASGIConnection[Any, Any, Any](scope) - cookie_keys = sorted(key for key in connection.cookies if self.config.key in key) + cookie_keys = sorted(key for key in connection.cookies if self.cookie_re.fullmatch(key)) if cookie_keys: data = [connection.cookies[key].encode("utf-8") for key in cookie_keys] # If these exceptions occur, the session must remain empty so do nothing.
diff --git a/tests/middleware/test_session_middleware.py b/tests/middleware/test_session_middleware.py --- a/tests/middleware/test_session_middleware.py +++ b/tests/middleware/test_session_middleware.py @@ -99,6 +99,27 @@ def handler(request: Request) -> None: assert "session-0" in response.cookies +def test_session_cookie_name_matching(session_middleware: SessionMiddleware) -> None: + session_data = {"foo": "bar"} + + @get("/") + def handler(request: Request) -> Dict[str, Any]: + return request.session + + @post("/") + def set_session_data(request: Request) -> None: + request.set_session(session_data) + + with create_test_client( + route_handlers=[handler, set_session_data], + middleware=[session_middleware.config.middleware], + ) as client: + client.post("/") + client.cookies[f"thisisnnota{session_middleware.config.key}cookie"] = "foo" + response = client.get("/") + assert response.json() == session_data + + @pytest.mark.parametrize("mutate", [False, True]) def test_load_session_cookies_and_expire_previous(mutate: bool, session_middleware: SessionMiddleware) -> None: """Should load session cookies into session from request and overwrite the
Bug: Cookies with the strings "session" in their name interfere with the session middleware **Describe the bug** If a request contains the a cookie with the name containing the string `session`, it will result in invalid session data **To Reproduce** ```python from secrets import token_bytes from typing import Any from starlite import Request, Starlite, get, post from starlite.middleware.session import SessionCookieConfig from starlite.testing import TestClient session_config = SessionCookieConfig(secret=token_bytes()) session_data = {"foo": "bar"} @get("/") def get_something(request: Request) -> dict[str, Any]: return request.session @post("/") def set_session_data(request: Request) -> None: request.set_session(session_data) app = Starlite( route_handlers=[get_something, set_session_data], middleware=[session_config.middleware], ) client = TestClient(app) assert client.post("/session").json() == session_data assert client.get("/session", cookies={"thisisnotasessioncookie": "foo"}).json() == session_data ``` **Additional context** This is happening because of [this line](this line: https://github.com/starlite-api/starlite/blob/main/starlite/middleware/session.py#L259). ```python cookie_keys = sorted(key for key in connection.cookies if self.config.key in key) ``` It is meant to check for multiple session cookies, in case data has to be stored in multiple cookies due to size constraints. In these cases, session cookies are created following the schema `session-<i>`, but this isnt' checked for. The line should be ```python cookie_keys = sorted(key for key in connection.cookies re.fullmatch(fr"{self.config.key}(?:-\d+)?", key)) ``` to only check for cookies following the exact pattern potentially set by the middleware (regex should be compiled on the middleware instance beforehand). Bug: Cookies with the strings "session" in their name interfere with the session middleware **Describe the bug** If a request contains the a cookie with the name containing the string `session`, it will result in invalid session data **To Reproduce** ```python from secrets import token_bytes from typing import Any from starlite import Request, Starlite, get, post from starlite.middleware.session import SessionCookieConfig from starlite.testing import TestClient session_config = SessionCookieConfig(secret=token_bytes()) session_data = {"foo": "bar"} @get("/") def get_something(request: Request) -> dict[str, Any]: return request.session @post("/") def set_session_data(request: Request) -> None: request.set_session(session_data) app = Starlite( route_handlers=[get_something, set_session_data], middleware=[session_config.middleware], ) client = TestClient(app) assert client.post("/session").json() == session_data assert client.get("/session", cookies={"thisisnotasessioncookie": "foo"}).json() == session_data ``` **Additional context** This is happening because of [this line](this line: https://github.com/starlite-api/starlite/blob/main/starlite/middleware/session.py#L259). ```python cookie_keys = sorted(key for key in connection.cookies if self.config.key in key) ``` It is meant to check for multiple session cookies, in case data has to be stored in multiple cookies due to size constraints. In these cases, session cookies are created following the schema `session-<i>`, but this isnt' checked for. The line should be ```python cookie_keys = sorted(key for key in connection.cookies re.fullmatch(fr"{self.config.key}(?:-\d+)?", key)) ``` to only check for cookies following the exact pattern potentially set by the middleware (regex should be compiled on the middleware instance beforehand).
2022-10-20T10:24:30
litestar-org/litestar
660
litestar-org__litestar-660
[ "655" ]
82409fde9ece30c385fc73698e66d1853f51cf12
diff --git a/starlite/types/partial.py b/starlite/types/partial.py --- a/starlite/types/partial.py +++ b/starlite/types/partial.py @@ -15,6 +15,7 @@ ) from pydantic import BaseModel, create_model +from pydantic.typing import is_classvar from typing_extensions import TypedDict, get_args from starlite.exceptions import ImproperlyConfiguredException @@ -88,6 +89,8 @@ def _create_partial_pydantic_model(cls, item: Type[BaseModel]) -> None: """ field_definitions: Dict[str, Tuple[Any, None]] = {} for field_name, field_type in get_type_hints(item).items(): + if is_classvar(field_type): + continue if not isinstance(field_type, GenericAlias) or NoneType not in field_type.__args__: field_definitions[field_name] = (Optional[field_type], None) else:
diff --git a/tests/__init__.py b/tests/__init__.py --- a/tests/__init__.py +++ b/tests/__init__.py @@ -5,8 +5,13 @@ from pydantic import BaseModel, Field from pydantic.dataclasses import dataclass as pydantic_dataclass from pydantic_factories import ModelFactory +from sqlalchemy import Column +from sqlalchemy.dialects.postgresql import INTEGER, JSONB, TEXT +from sqlalchemy.orm import declarative_base from typing_extensions import TypedDict +Base = declarative_base() + class Species(str, Enum): DOG = "Dog" @@ -65,3 +70,14 @@ class TypedDictPerson(TypedDict): optional: Optional[str] complex: Dict[str, List[Dict[str, str]]] pets: Optional[List[Pet]] + + +class Car(Base): + __tablename__ = "db_cars" + + id = Column(INTEGER, primary_key=True) + year = Column(INTEGER) + make = Column(TEXT) + model = Column(TEXT) + horsepower = Column(INTEGER) + color_codes = Column(JSONB) diff --git a/tests/dto_factory/test_dto_factory_partials.py b/tests/dto_factory/test_dto_factory_partials.py new file mode 100644 --- /dev/null +++ b/tests/dto_factory/test_dto_factory_partials.py @@ -0,0 +1,45 @@ +from starlite import DTOFactory +from starlite.plugins.sql_alchemy import SQLAlchemyPlugin +from starlite.types.partial import Partial +from tests import Car, Person + +dto_factory = DTOFactory(plugins=[SQLAlchemyPlugin()]) + + +def test_partial_dto_pydantic() -> None: + dto_partial_person = Partial[Person] + bob = dto_partial_person(first_name="Bob") # type: ignore + assert bob.first_name == "Bob" # type: ignore + + +def test_partial_dto_sqlalchemy_model() -> None: + car_one = { + "id": 1, + "year": 2022, + "make": "Ferrari", + "model": "488 Challenge Evo", + "horsepower": 670, + "color_codes": { + "red": "Rosso corsa", + "black": "Nero", + "yellow": "Giallo Modena", + }, + } + + car_two = { + "id": 2, + "year": 1969, + "make": "Ford", + "model": "GT40", + "horsepower": 380, + } + + # Test for non-partial DTO + dto_car = dto_factory("dto_cars", Car) + ferrari = dto_car(**car_one) + assert ferrari.year == 2022 # type: ignore + + # Test for partial DTO + partial_dto_car = Partial[dto_car] # type: ignore + ford = partial_dto_car(**car_two) + assert ford.make == "Ford" # type: ignore
Partial[DTO] Exception: typing.ClassVar[bool] is not valid as type argument **Describe the bug** When creating a `Partial[DTO]`, I get the following exception: `Exception: typing.ClassVar[bool] is not valid as type argument` The exception appears to be thrown in the `partials.py` file, from the 3rd line copied here: ``` if item not in cls._models: if is_class_and_subclass(item, BaseModel): cls._create_partial_pydantic_model(item=item) ``` **To Reproduce** Here's a minimal example to reproduce. I'm using Python 3.10.6. ``` from sqlalchemy import Column from sqlalchemy.dialects.postgresql import ( INTEGER, JSONB, TIMESTAMP, ) from sqlalchemy.orm import declarative_base from starlite import DTOFactory from starlite.plugins.sql_alchemy import SQLAlchemyPlugin from starlite.types.partial import Partial Base = declarative_base() dto_factory = DTOFactory(plugins=[SQLAlchemyPlugin()]) class DTO_ORM(Base): __tablename__ = "some_table" id = Column(INTEGER, primary_key=True) value = Column(JSONB) logs = Column(JSONB) timestamp = Column(TIMESTAMP) DTO_MODEL = dto_factory("DTO_MODEL", DTO_ORM) partial_dto = Partial[DTO_MODEL] data = {"id": 789} partial_dto(**data) ``` **Additional context** I believe I've implemented this code correctly, but there aren't a lot of examples for how to use DTOs or Partials, so please let me know if something is wrong with the code. Docs: https://starlite-api.github.io/starlite/usage/11-data-transfer-objects/#partial-dtos
I just played with the code in the tests folder... it seems like this exception does not occur using DTO's created Pydantic models. So maybe it's isolated to DTO's created by SQL Alchemy/ORM models. **This works:** ``` import json from dataclasses import dataclass as vanilla_dataclass from enum import Enum from typing import Any, Dict, List, Optional import pytest from pydantic import BaseModel, Field from pydantic.dataclasses import dataclass as pydantic_dataclass from pydantic_factories import ModelFactory from starlette.status import HTTP_201_CREATED from starlite import DTOFactory, post from starlite.plugins.sql_alchemy import SQLAlchemyPlugin from starlite.testing import create_test_client from starlite.types.partial import Partial from typing_extensions import TypedDict # from tests import Person, TypedDictPerson, VanillaDataClassPerson # from tests.plugins.sql_alchemy_plugin import Pet, WildAnimal # Base = declarative_base() dto_factory = DTOFactory(plugins=[SQLAlchemyPlugin()]) class Person(BaseModel): first_name: str last_name: str id: str optional: Optional[str] complex: Dict[str, List[Dict[str, str]]] pets: Optional[List[Pet]] = None dto_person = dto_factory("dto_person", Person) dto_partial_person = Partial[Person] dto_partial_person(first_name="Bob") ``` **Returns:** ``` PartialPerson(first_name='Bob', last_name=None, id=None, optional=None, complex=None, pets=None) ```
2022-10-23T12:18:57
litestar-org/litestar
695
litestar-org__litestar-695
[ "693" ]
95379f102be249f3c9453fbf9d216a41eede2d6f
diff --git a/starlite/response/base.py b/starlite/response/base.py --- a/starlite/response/base.py +++ b/starlite/response/base.py @@ -255,7 +255,7 @@ def encoded_headers(self) -> List[Tuple[bytes, bytes]]: content_type = self.media_type encoded_headers = [ - *((k.lower().encode("latin-1"), str(v).lower().encode("latin-1")) for k, v in self.headers.items()), + *((k.lower().encode("latin-1"), str(v).encode("latin-1")) for k, v in self.headers.items()), *((b"set-cookie", cookie.to_header(header="").encode("latin-1")) for cookie in self.cookies), (b"content-type", content_type.encode("latin-1")), ]
diff --git a/tests/response/test_base_response.py b/tests/response/test_base_response.py --- a/tests/response/test_base_response.py +++ b/tests/response/test_base_response.py @@ -31,6 +31,18 @@ def handler() -> Response: assert response.headers["content-type"] == "text/plain; charset=utf-8" +def test_response_headers_do_not_lowercase_values() -> None: + # reproduces: https://github.com/starlite-api/starlite/issues/693 + + @get("/") + def handler() -> Response: + return Response(content="hello world", media_type=MediaType.TEXT, headers={"foo": "BaR"}) + + with create_test_client(handler) as client: + response = client.get("/") + assert response.headers["foo"] == "BaR" + + def test_set_cookie() -> None: @get("/") def handler() -> Response: diff --git a/tests/response/test_file_response.py b/tests/response/test_file_response.py --- a/tests/response/test_file_response.py +++ b/tests/response/test_file_response.py @@ -79,7 +79,7 @@ def test_file_response_with_chinese_filename(tmpdir: Path) -> None: app = FileResponse(path=path, filename=filename) client = TestClient(app) response = client.get("/") - expected_disposition = "attachment; filename*=utf-8''%e4%bd%a0%e5%a5%bd.txt" + expected_disposition = "attachment; filename*=utf-8''%E4%BD%A0%E5%A5%BD.txt" assert response.status_code == HTTP_200_OK assert response.content == content assert response.headers["content-disposition"] == expected_disposition
Bug: Header values should not be lowercased **Describe the bug** Headers keys and values are lowercased before being rendered. While lowercasing key is fine (as per HTTP2 spec), lowercasing values should not be done. For my use case, integrating with a payment provider involves passing a transaction ID as a header. This ID contains lowercase, uppercase letters, and is not case-insensitive. **To Reproduce** 1. Create a new route_handler. 2. In the route_handler, modify the response: `response.headers["Foo"] = "Bar"` . 3. Observe that the key and value are returned as lowercase: ![2022-10-27_16-23](https://user-images.githubusercontent.com/546693/198312809-fc5b8947-be88-4354-b909-033270ae188f.png) 4. While reporting this, I noticed that `date` and `vary` headers are not lowercased. **Additional context** Looking at the Git history, it seems that originally Starlette was used for handling the responses. I thought that Starlette might also have this behaviour, but they do not lowercase the header values. See https://github.com/encode/starlette/blob/fa737beb2838f568fe2477e2316a7fdf3d3eb257/starlette/responses.py#L72 . The relevant code in Starlite is here: https://github.com/starlite-api/starlite/blob/95379f102be249f3c9453fbf9d216a41eede2d6f/starlite/response/base.py#L257
yup, will fix. @provinzkraut can you take this on quickly and add it to the release you are doing? @Goldziher will do. Just waiting for a comment from you on the open conversations, then it's ready to go
2022-10-27T15:01:57
litestar-org/litestar
699
litestar-org__litestar-699
[ "687" ]
366c630a3e2ed49b320b6bf8538356f4ca70390c
diff --git a/starlite/plugins/sql_alchemy/plugin.py b/starlite/plugins/sql_alchemy/plugin.py --- a/starlite/plugins/sql_alchemy/plugin.py +++ b/starlite/plugins/sql_alchemy/plugin.py @@ -390,7 +390,9 @@ def to_pydantic_model_class(self, model_class: Type[DeclarativeMeta], **kwargs: # we are treating back-references as any to avoid infinite recursion else: field_definitions[name] = (Any, None) - self._model_namespace_map[model_name] = create_model(model_name, **field_definitions) + self._model_namespace_map[model_name] = create_model( + model_name, __config__=type("Config", (), {"orm_mode": True}), **field_definitions + ) for related_entity_class in related_entity_classes: self.to_pydantic_model_class(model_class=related_entity_class) model = self._model_namespace_map[model_name] @@ -426,7 +428,7 @@ def to_dict(self, model_instance: "DeclarativeMeta") -> Dict[str, Any]: pydantic_model = self._model_namespace_map.get(model_class.__qualname__) or self.to_pydantic_model_class( model_class=model_class ) - return pydantic_model(**{field: getattr(model_instance, field) for field in pydantic_model.__fields__}).dict() + return pydantic_model.from_orm(model_instance).dict() # type:ignore[pydantic-unexpected] def from_dict(self, model_class: "Type[DeclarativeMeta]", **kwargs: Any) -> DeclarativeMeta: """Given a dictionary of kwargs, return an instance of the given
diff --git a/tests/plugins/sql_alchemy_plugin/test_sql_alchemy_relationships.py b/tests/plugins/sql_alchemy_plugin/test_sql_alchemy_relationships.py --- a/tests/plugins/sql_alchemy_plugin/test_sql_alchemy_relationships.py +++ b/tests/plugins/sql_alchemy_plugin/test_sql_alchemy_relationships.py @@ -4,7 +4,7 @@ from typing_extensions import get_args from starlite.plugins.sql_alchemy import SQLAlchemyPlugin -from tests.plugins.sql_alchemy_plugin import Pet, User +from tests.plugins.sql_alchemy_plugin import Company, Pet, User def test_relationship() -> None: @@ -23,7 +23,11 @@ def test_relationship() -> None: def test_table_name() -> None: - pet_table = Pet - user_table = User - assert pet_table.__tablename__ == "pet" - assert user_table.__tablename__ == "user" + assert Pet.__tablename__ == "pet" + assert User.__tablename__ == "user" + + +def test_plugin_to_dict_with_relationship() -> None: + plugin = SQLAlchemyPlugin() + user = User(id=1, name="A. Person", company=Company(id=1, name="Mega Corp", worth=1.0)) + plugin.to_dict(user) # type:ignore[arg-type]
Bug: SQLAlchemy Plugin DTO cannot reflect relationships. Hi folks, not sure if this really a bug or a feature, but Im not able to make a DTO from a instance having a simple relationship. I do have very often the case where I just want to reflect the 1 in my sa model and explicitly not the n because it will soon pollute the namespace. And it is not that uncommon as per [sa doc](https://docs.sqlalchemy.org/en/14/orm/basic_relationships.html#many-to-one) I could work around by expunging the orm model form the its session and set owner to None. But this implies a lot of additional problems. P. S. I really would encourage you to document only working examples. Code below is a copy from sa plugin doc, which does not work without adding a proper tablename. cheers... ```python """ Showing exception on simple relationships avoiding optional back_populate argument. """ from sqlalchemy import Column, Float, ForeignKey, Integer, String from sqlalchemy.orm import relationship, declarative_base from starlite.plugins.sql_alchemy import SQLAlchemyPlugin from starlite import DTOFactory Base = declarative_base() dto_factory = DTOFactory(plugins=[SQLAlchemyPlugin()]) class Pet(Base): __tablename__ = "pet" # needs to added to example, or change base definition accordingly. id = Column(Integer, primary_key=True) name = Column(String) age = Column(Float) owner_id = Column(Integer, ForeignKey("user.id")) owner = relationship("User") # , back_populates="pets") class User(Base): __tablename__ = "user" # needs to added to example, or change base definition accordingly. id = Column(Integer, primary_key=True) name = Column(String, default="moishe") # pets = relationship( # "Pet", # back_populates="owner", # ) UserDTO = dto_factory("UserDTO", User) PetDTO = dto_factory("PetDTO", Pet) mike = User(id=1, name="Mike") kitty = Pet(id=1, name="kitty", age=4.2) kitty.owner = mike pet_dto = PetDTO.from_model_instance(kitty) # prints: # pydantic.error_wrappers.ValidationError: 1 validation error for Pet # owner # value is not a valid dict (type=type_error.dict) ```
Hi @cloasdata - I would like to ask either @peterschutt or @cofin to look into this when they have time. Yep I'll be able to have a look
2022-10-28T12:22:32
litestar-org/litestar
741
litestar-org__litestar-741
[ "740" ]
34740bd61493b970fe52005c4922a9f4a3a7d83c
diff --git a/starlite/middleware/logging.py b/starlite/middleware/logging.py --- a/starlite/middleware/logging.py +++ b/starlite/middleware/logging.py @@ -176,6 +176,7 @@ def extract_response_data(self, scope: "Scope") -> Dict[str, Any]: ) ) for key in self.config.response_log_fields: + value: Any value = extracted_data.get(key) if not self.is_struct_logger and isinstance(value, (dict, list, tuple, set)): value = dumps(value, default=serializer, option=OPT_SERIALIZE_NUMPY | OPT_OMIT_MICROSECONDS) diff --git a/starlite/utils/extractors.py b/starlite/utils/extractors.py --- a/starlite/utils/extractors.py +++ b/starlite/utils/extractors.py @@ -45,7 +45,7 @@ def obfuscate(values: Dict[str, Any], fields_to_obfuscate: Set[str]) -> Dict[str "path", "method", "content_type", "headers", "cookies", "query", "path_params", "body", "scheme", "client" ] -ResponseExtractorField = Literal["status_code", "method", "headers", "body", "cookies"] +ResponseExtractorField = Literal["status_code", "headers", "body", "cookies"] class ExtractedRequestData(TypedDict, total=False):
Bug: "method" not extracted response field https://github.com/starlite-api/starlite/blob/34740bd61493b970fe52005c4922a9f4a3a7d83c/starlite/utils/extractors.py#L48
2022-11-03T06:40:54
litestar-org/litestar
771
litestar-org__litestar-771
[ "770" ]
443425e258c22d2812f8abb87c52a0015798ce1c
diff --git a/starlite/openapi/path_item.py b/starlite/openapi/path_item.py --- a/starlite/openapi/path_item.py +++ b/starlite/openapi/path_item.py @@ -1,3 +1,4 @@ +from inspect import cleandoc from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, cast from pydantic_openapi_schema.v3_1_0.operation import Operation @@ -31,7 +32,7 @@ def get_description_for_handler(route_handler: "HTTPRouteHandler", use_handler_d """ handler_description = route_handler.description if handler_description is None and use_handler_docstrings: - return route_handler.fn.__doc__ + return cleandoc(route_handler.fn.__doc__) if route_handler.fn.__doc__ else None return handler_description
diff --git a/tests/openapi/test_path_item.py b/tests/openapi/test_path_item.py --- a/tests/openapi/test_path_item.py +++ b/tests/openapi/test_path_item.py @@ -41,3 +41,10 @@ def test_create_path_item_use_handler_docstring_true(route: HTTPRoute) -> None: assert schema.get.description == "Description in docstring." assert schema.patch assert schema.patch.description == "Description in decorator" + assert schema.put + assert schema.put.description + # make sure multiline docstring is fully included + assert "Line 3." in schema.put.description + # make sure internal docstring indentation used to line up with the code + # is removed from description + assert " " not in schema.put.description diff --git a/tests/openapi/utils.py b/tests/openapi/utils.py --- a/tests/openapi/utils.py +++ b/tests/openapi/utils.py @@ -109,6 +109,10 @@ def partial_update_person(self, person_id: str, data: Partial[Person]) -> Person @put(path="/{person_id:str}") def update_person(self, person_id: str, data: Person) -> Person: + """Multiline docstring example. + + Line 3. + """ return data @delete(path="/{person_id:str}")
Properly indented docstrings result in incorrectly rendered Markdown in openapi docs **Describe the bug** A properly formatted docstring is indented to match the indentation of the function or method. The markdown rendering that is passed into the API docs seems to be interpreting these indentations in such a way that the markdown is not properly formatted unless the docstring is out-dented to an unconventional flush left. **To Reproduce** I have the following function definition with docstring: ``` async def content_classifier_model_details(model_name:str) -> ModelClassDetailsResponse: """Retrieve the variants and versions of a group of content classifier models for a given named classification. Models can be specified at the `classify` endpoint as follows: - **Class name only** (`model_name`). E.g. `climate_action`. Will utilize the default model as indicated by the default flag in the model details. _This format is provided primarily for development and exploratory purposes._ In production code, it is recommended that the variant be specified. - **Class with variant** (`name-variant`). E.g. `climate_action-nx`. Will utilize the current version of the specified variant as indicated by the `current` field in the model details. - **Full versioned identifier** (`name-variant-version`). E.g. `climate_action-nx-1` is useful for pinning your application to a specific historical version. """ ``` The result is shown in the screenshot titled incorrect-markdown-render.png. The expected rendering is shown in correct-markdown-render.png which can be achieved by the following unconventional docstring format: ``` async def content_classifier_model_details(model_name:str) -> ModelClassDetailsResponse: """Retrieve the variants and versions of a group of content classifier models for a given named classification. Models can be specified at the `classify` endpoint as follows: - **Class name only** (`model_name`). E.g. `climate_action`. Will utilize the default model as indicated by the default flag in the model details. _This format is provided primarily for development and exploratory purposes._ In production code, it is recommended that the variant be specified. - **Class with variant** (`name-variant`). E.g. `climate_action-nx`. Will utilize the current version of the specified variant as indicated by the `current` field in the model details. - **Full versioned identifier** (`name-variant-version`). E.g. `climate_action-nx-1` is useful for pinning your application to a specific historical version. """ ``` ## incorrect-markdown-render <img width="579" alt="incorrect-markdown-render" src="https://user-images.githubusercontent.com/307713/200467063-af74141c-f289-49f0-afe6-1aa28e9bea73.png"> ## correct-markdown-render (achieved via unconventional docstring out-denting) <img width="571" alt="correct-markdown-render" src="https://user-images.githubusercontent.com/307713/200467064-349dfbda-0a21-4d99-8929-ab3a9f51323f.png">
2022-11-08T04:27:30
litestar-org/litestar
784
litestar-org__litestar-784
[ "783", "783" ]
f36d16a0c37f20fd0a4a92cd35d363b25aed4b6b
diff --git a/starlite/static_files/base.py b/starlite/static_files/base.py --- a/starlite/static_files/base.py +++ b/starlite/static_files/base.py @@ -8,6 +8,7 @@ from starlite.utils.file import FileSystemAdapter if TYPE_CHECKING: + from typing_extensions import Literal from starlite.types import Receive, Scope, Send from starlite.types.composite_types import PathType @@ -61,12 +62,15 @@ async def __call__(self, scope: "Scope", receive: "Receive", send: "Send") -> No filename = split_path[-1] joined_path = join(*split_path) # noqa: PL118 resolved_path, fs_info = await self.get_fs_info(directories=self.directories, file_path=joined_path) + content_disposition_type: "Literal['inline', 'attachment']" = "attachment" - if fs_info and fs_info["type"] == "directory" and self.is_html_mode: - filename = "index.html" - resolved_path, fs_info = await self.get_fs_info( - directories=self.directories, file_path=join(resolved_path or joined_path, filename) - ) + if self.is_html_mode: + content_disposition_type = "inline" + if fs_info and fs_info["type"] == "directory": + filename = "index.html" + resolved_path, fs_info = await self.get_fs_info( + directories=self.directories, file_path=join(resolved_path or joined_path, filename) + ) if fs_info and fs_info["type"] == "file": await FileResponse( @@ -75,6 +79,7 @@ async def __call__(self, scope: "Scope", receive: "Receive", send: "Send") -> No file_system=self.adapter.file_system, filename=filename, is_head_response=scope["method"] == "HEAD", + content_disposition_type=content_disposition_type, )(scope, receive, send) return @@ -89,6 +94,7 @@ async def __call__(self, scope: "Scope", receive: "Receive", send: "Send") -> No filename=filename, is_head_response=scope["method"] == "HEAD", status_code=HTTP_404_NOT_FOUND, + content_disposition_type=content_disposition_type, )(scope, receive, send) return
diff --git a/tests/static_files/test_file_serving_resolution.py b/tests/static_files/test_file_serving_resolution.py --- a/tests/static_files/test_file_serving_resolution.py +++ b/tests/static_files/test_file_serving_resolution.py @@ -149,3 +149,16 @@ def test_static_files_response_mimetype(tmpdir: "Path", extension: str) -> None: assert expected_mime_type assert response.status_code == HTTP_200_OK assert response.headers["content-type"].startswith(expected_mime_type) + + [email protected]("html_mode,disposition", [(True, "inline"), (False, "attachment")]) +def test_static_files_response_content_disposition(tmpdir: "Path", html_mode: bool, disposition: str) -> None: + fn = "test.txt" + path = tmpdir / fn + path.write_text("content", "utf-8") + static_files_config = StaticFilesConfig(path="/static", directories=[tmpdir], html_mode=html_mode) + + with create_test_client([], static_files_config=static_files_config) as client: + response = client.get(f"/static/{fn}") + assert response.status_code == HTTP_200_OK + assert response.headers["content-disposition"].startswith(disposition) diff --git a/tests/static_files/test_html_mode.py b/tests/static_files/test_html_mode.py --- a/tests/static_files/test_html_mode.py +++ b/tests/static_files/test_html_mode.py @@ -26,6 +26,7 @@ def test_staticfiles_is_html_mode(tmpdir: "Path", file_system: "FileSystemProtoc assert response.status_code == HTTP_200_OK assert response.text == "content" assert response.headers["content-type"] == "text/html; charset=utf-8" + assert response.headers["content-disposition"].startswith("inline") @pytest.mark.parametrize("file_system", (BaseLocalFileSystem(), LocalFileSystem()))
Bug: StaticFiles sends files as `content-disposition: 'attachment'` in html-mode **Describe the bug** When using `StaticFiles` in html-mode, files are being sent with `content-disposition: 'attachment'` **To Reproduce** Create an `html/index.html` file. Run: ```python from starlite import Starlite, StaticFilesConfig, TestClient app = Starlite( static_files_config=[StaticFilesConfig(path="/", directories=["html"], html_mode=True)], route_handlers=[] ) with TestClient(app=app) as client: res = client.get("/index.html") assert not res.headers["content-disposition"].startswith("attachment") ``` Bug: StaticFiles sends files as `content-disposition: 'attachment'` in html-mode **Describe the bug** When using `StaticFiles` in html-mode, files are being sent with `content-disposition: 'attachment'` **To Reproduce** Create an `html/index.html` file. Run: ```python from starlite import Starlite, StaticFilesConfig, TestClient app = Starlite( static_files_config=[StaticFilesConfig(path="/", directories=["html"], html_mode=True)], route_handlers=[] ) with TestClient(app=app) as client: res = client.get("/index.html") assert not res.headers["content-disposition"].startswith("attachment") ```
2022-11-10T14:01:24
litestar-org/litestar
806
litestar-org__litestar-806
[ "802" ]
5be8c46427d254aca457d3cf192cf3a9c7b5e3ad
diff --git a/starlite/signature.py b/starlite/signature.py --- a/starlite/signature.py +++ b/starlite/signature.py @@ -41,7 +41,7 @@ UNDEFINED_SENTINELS = {Undefined, Signature.empty} SKIP_NAMES = {"self", "cls"} -SKIP_VALIDATION_NAMES = {"request", "socket", "state", "scope"} +SKIP_VALIDATION_NAMES = {"request", "socket", "state", "scope", "receive", "send"} class SignatureModel(BaseModel): @@ -178,6 +178,7 @@ class SignatureModelFactory: "dependency_name_set", "field_definitions", "field_plugin_mappings", + "fn_module_name", "fn_name", "plugins", "signature", @@ -194,7 +195,8 @@ def __init__(self, fn: "AnyCallable", plugins: List["PluginProtocol"], dependenc if fn is None: raise ImproperlyConfiguredException("Parameter `fn` to `SignatureModelFactory` cannot be `None`.") self.signature = Signature.from_callable(fn) - self.fn_name = fn.__name__ if hasattr(fn, "__name__") else "anonymous" + self.fn_name = getattr(fn, "__name__", "anonymous") + self.fn_module_name = getattr(fn, "__module__", "pydantic.main") self.plugins = plugins self.field_plugin_mappings: Dict[str, PluginMapping] = {} self.field_definitions: Dict[str, Any] = {} @@ -324,7 +326,10 @@ def create_signature_model(self) -> Type[SignatureModel]: parameter.annotation = self.get_type_annotation_from_plugin(parameter, plugin) self.field_definitions[parameter.name] = self.create_field_definition_from_parameter(parameter) model: Type[SignatureModel] = create_model( - self.fn_name + "_signature_model", __base__=SignatureModel, **self.field_definitions + self.fn_name + "_signature_model", + __base__=SignatureModel, + __module__=self.fn_module_name, + **self.field_definitions, ) model.return_annotation = self.signature.return_annotation model.field_plugin_mappings = self.field_plugin_mappings
diff --git a/tests/conftest.py b/tests/conftest.py --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,3 +1,5 @@ +import importlib.util +import sys from os import environ, urandom from pathlib import Path from sys import version_info @@ -10,9 +12,11 @@ Generator, Optional, Tuple, + TypeVar, Union, cast, ) +from uuid import uuid4 import fakeredis.aioredis # pyright: ignore import pytest @@ -56,6 +60,10 @@ from tests.mocks import FakeAsyncMemcached if TYPE_CHECKING: + from types import ModuleType + + from pytest import MonkeyPatch + from starlite import Starlite from starlite.types import ( AnyIOBackend, @@ -312,7 +320,7 @@ def inner( session: "ScopeSession" = None, state: Optional[Dict[str, Any]] = None, user: Any = None, - **kwargs: Dict[str, Any] + **kwargs: Dict[str, Any], ) -> "Scope": scope = { "app": app, @@ -344,3 +352,35 @@ def inner( @pytest.fixture def scope(create_scope: Callable[..., "Scope"]) -> "Scope": return create_scope() + + [email protected] +def create_module(tmp_path: Path, monkeypatch: "MonkeyPatch") -> "Callable[[str], ModuleType]": + """Utility fixture for dynamic module creation.""" + + def wrapped(source: str) -> "ModuleType": + """ + + Args: + source: Source code as a string. + + Returns: + An imported module. + """ + T = TypeVar("T") + + def not_none(val: Union[T, Optional[T]]) -> T: + assert val is not None + return val + + module_name = uuid4().hex + path = tmp_path / f"{module_name}.py" + path.write_text(source) + # https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly + spec = not_none(importlib.util.spec_from_file_location(module_name, path)) + module = not_none(importlib.util.module_from_spec(spec)) + monkeypatch.setitem(sys.modules, module_name, module) + not_none(spec.loader).exec_module(module) + return module + + return wrapped diff --git a/tests/test_signature.py b/tests/test_signature.py --- a/tests/test_signature.py +++ b/tests/test_signature.py @@ -6,7 +6,7 @@ from pydantic import BaseModel, ValidationError from pydantic.error_wrappers import ErrorWrapper -from starlite import HTTPException, Provide, get +from starlite import Provide, get from starlite.connection import WebSocket from starlite.datastructures import URL from starlite.exceptions import ( @@ -17,12 +17,16 @@ from starlite.params import Dependency from starlite.signature import SignatureModel, SignatureModelFactory from starlite.status_codes import HTTP_204_NO_CONTENT -from starlite.testing import RequestFactory, create_test_client +from starlite.testing import RequestFactory, TestClient, create_test_client from tests.plugins.test_base import AModel, APlugin if TYPE_CHECKING: + from types import ModuleType + from typing import Callable + from pydantic.error_wrappers import ErrorDict + from starlite import HTTPException from starlite.plugins.base import PluginProtocol from starlite.types import AnyCallable @@ -236,3 +240,29 @@ def get_handler(p: int) -> None: str(e) == "<ExceptionInfo 500 - ImproperlyConfiguredException - Error creating signature model for 'get_handler': 'a type error' tblen=2>" ) + + +def test_signature_model_resolves_forward_ref_annotations(create_module: "Callable[[str], ModuleType]") -> None: + module = create_module( + """ +from __future__ import annotations +from pydantic import BaseModel +from starlite import Provide, Starlite, get + +class Test(BaseModel): + hello: str + +async def get_dep() -> Test: + return Test(hello="world") + +@get("/", dependencies={"test": Provide(get_dep)}) +def hello_world(test: Test) -> Test: + return test + +app = Starlite(route_handlers=[hello_world], openapi_config=None) +""" + ) + with TestClient(app=module.app) as client: + resp = client.get("/") + assert resp.status_code == 200 + assert resp.json() == {"hello": "world"}
Enhancement: resolve forward refs when producing signature models We need to support where users declare `from __future__ import annotations` in modules where handlers and dependencies are declared.
2022-11-14T13:39:38
litestar-org/litestar
818
litestar-org__litestar-818
[ "816" ]
8db49cb1d12cb7072d9fa5b6156880b982a77524
diff --git a/starlite/asgi/routing_trie/traversal.py b/starlite/asgi/routing_trie/traversal.py --- a/starlite/asgi/routing_trie/traversal.py +++ b/starlite/asgi/routing_trie/traversal.py @@ -91,7 +91,7 @@ def traverse_route_map( has_path_param = PathParameterSentinel in current_node["child_keys"] if not path_components: - if has_path_param or not current_node["asgi_handlers"]: + if not current_node["asgi_handlers"]: raise NotFoundException() return current_node, path_params @@ -171,7 +171,7 @@ def parse_scope_to_route(root_node: "RouteTrieNode", scope: "Scope", plain_route current_node, path_params = traverse_route_map( current_node=root_node, path=path, - path_components=deque([component for component in path.split("/") if component]), + path_components=deque(component for component in path.split("/") if component), path_params=[], scope=scope, )
diff --git a/tests/routing/test_path_resolution.py b/tests/routing/test_path_resolution.py --- a/tests/routing/test_path_resolution.py +++ b/tests/routing/test_path_resolution.py @@ -1,4 +1,4 @@ -from typing import Any, Callable, Optional, Type +from typing import Any, Callable, List, Optional, Type import pytest @@ -206,3 +206,21 @@ def handler_fn(name: str) -> str: if response.status_code == HTTP_200_OK: assert response.text == expected_param + + +def test_no_404_where_list_route_has_handlers_and_child_route_has_path_param() -> None: + # https://github.com/starlite-api/starlite/issues/816 + + # the error condition requires the path to not be a plain route, hence the prefixed path parameters + @get("/{a:str}/b") + def get_list() -> List[str]: + return ["ok"] + + @get("/{a:str}/b/{c:int}") + def get_member() -> str: + return "ok" + + with create_test_client(route_handlers=[get_list, get_member]) as client: + resp = client.get("/scope/b") + assert resp.status_code == 200 + assert resp.json() == ["ok"]
Endpoints 404 when using path parameters in Controller path **Describe the bug** When using a path parameter in the base path for a Controller, endpoints without further path parameters return 404. In the example provided, get_user functions as-is, while list_users only functions if get_user is deleted. **To Reproduce** Minimal example: ```python from starlite import Controller, get from pydantic import BaseModel, UUID4, Field from uuid import uuid4 class User(BaseModel): id: UUID4 = Field(default_factory=uuid4) class UserController(Controller): path = "/{realm:str}/users" @get() async def list_users(self, realm: str) -> list[User]: return [User()] @get(path="/{user_id:uuid}") async def get_user(self, realm: str, user_id: UUID4) -> User: return User() ``` **Additional context** Version info: ``` $ python3 --version Python 3.11.0 $ pip freeze anyio==3.6.2 certifi==2022.9.24 click==8.1.3 dnspython==2.2.1 email-validator==1.3.0 Faker==15.3.2 h11==0.12.0 httpcore==0.15.0 httpx==0.23.0 idna==3.4 multidict==6.0.2 orjson==3.8.1 pydantic==1.10.2 pydantic-factories==1.15.0 pydantic-openapi-schema==1.3.0 python-dateutil==2.8.2 PyYAML==6.0 rfc3986==1.5.0 six==1.16.0 sniffio==1.3.0 starlite==1.39.0 starlite-multipart==1.2.0 typing_extensions==4.4.0 uvicorn==0.19.0 ```
@all-contributors please add @sssssss340 for bug @peterschutt I've put up [a pull request](https://github.com/starlite-api/starlite/pull/817) to add @sssssss340! :tada:
2022-11-18T02:17:55
litestar-org/litestar
842
litestar-org__litestar-842
[ "841" ]
06cff89fc7f0fea80b9a22d91f7c842e98c35685
diff --git a/starlite/middleware/session/sqlalchemy_backend.py b/starlite/middleware/session/sqlalchemy_backend.py --- a/starlite/middleware/session/sqlalchemy_backend.py +++ b/starlite/middleware/session/sqlalchemy_backend.py @@ -31,7 +31,7 @@ class SessionModelMixin: """Mixin for session storage.""" session_id: Mapped[str] = sa.Column(sa.String, nullable=False, unique=True, index=True) # pyright: ignore - data: Mapped[bytes] = sa.Column(sa.BLOB, nullable=False) # pyright: ignore + data: Mapped[bytes] = sa.Column(sa.LargeBinary, nullable=False) # pyright: ignore expires: Mapped[datetime] = sa.Column(sa.DateTime, nullable=False) # pyright: ignore @hybrid_property
SQLAlchemy Session backend uses wrong column type in `SessionModelMixin` **Describe the bug** The SQLAlchem session backend uses `BLOB` as the datatype in the `SessionModelMixin`, which is not compatible with all databases.
2022-11-22T14:15:38
litestar-org/litestar
843
litestar-org__litestar-843
[ "840", "840" ]
06cff89fc7f0fea80b9a22d91f7c842e98c35685
diff --git a/starlite/middleware/session/sqlalchemy_backend.py b/starlite/middleware/session/sqlalchemy_backend.py --- a/starlite/middleware/session/sqlalchemy_backend.py +++ b/starlite/middleware/session/sqlalchemy_backend.py @@ -199,6 +199,7 @@ async def delete_expired(self) -> None: """ async with self._create_sa_session() as sa_session: await sa_session.execute(sa.delete(self._model).where(self._model.expired)) + await sa_session.commit() class SQLAlchemyBackend(BaseSQLAlchemyBackend[SASession]): @@ -290,6 +291,7 @@ async def delete_all(self) -> None: def _delete_expired_sync(self) -> None: sa_session = self._create_sa_session() sa_session.execute(sa.delete(self._model).where(self._model.expired)) + sa_session.commit() async def delete_expired(self) -> None: """Delete all expired session from the database.
Flaky test I think this is a flaky test failure: ```python ____________________ test_sqlalchemy_backend_delete_expired ____________________ sqlalchemy_session_backend = <starlite.middleware.session.sqlalchemy_backend.SQLAlchemyBackend object at 0x7f9210794cc0> async def test_sqlalchemy_backend_delete_expired(sqlalchemy_session_backend: "SQLAlchemyBackend") -> None: await sqlalchemy_session_backend.set("foo", generate_session_data()) await sqlalchemy_session_backend.set("bar", generate_session_data()) session = sqlalchemy_session_backend._create_sa_session() model = sqlalchemy_session_backend.config.model session.execute( sa.update(model) .where(model.session_id == "foo") .values(expires=datetime.datetime.utcnow() - datetime.timedelta(days=60)) ) await sqlalchemy_session_backend.delete_expired() > assert not await sqlalchemy_session_backend.get("foo") E assert not b'{"47c49f1fa0a29b0e994338a22e32b3c79ca0391a4e55205dac411f173e7e1efe":"8cbd4cf924a42dcb80965706b0fad6af6f9afabc2711365cbe3ba20cdb8ce0c5"}' tests/middleware/session/test_server_backends.py:130: AssertionError ``` Flaky test I think this is a flaky test failure: ```python ____________________ test_sqlalchemy_backend_delete_expired ____________________ sqlalchemy_session_backend = <starlite.middleware.session.sqlalchemy_backend.SQLAlchemyBackend object at 0x7f9210794cc0> async def test_sqlalchemy_backend_delete_expired(sqlalchemy_session_backend: "SQLAlchemyBackend") -> None: await sqlalchemy_session_backend.set("foo", generate_session_data()) await sqlalchemy_session_backend.set("bar", generate_session_data()) session = sqlalchemy_session_backend._create_sa_session() model = sqlalchemy_session_backend.config.model session.execute( sa.update(model) .where(model.session_id == "foo") .values(expires=datetime.datetime.utcnow() - datetime.timedelta(days=60)) ) await sqlalchemy_session_backend.delete_expired() > assert not await sqlalchemy_session_backend.get("foo") E assert not b'{"47c49f1fa0a29b0e994338a22e32b3c79ca0391a4e55205dac411f173e7e1efe":"8cbd4cf924a42dcb80965706b0fad6af6f9afabc2711365cbe3ba20cdb8ce0c5"}' tests/middleware/session/test_server_backends.py:130: AssertionError ```
Ugh, this again. I thought I fixed it last time. Looks like I did not. I'll take care of it. Thanks! I really didn't look at it at all, just dumped it here so I didn't forget about it, apologies if a dup. Actually ran into it twice today. Well, if you encountered it again it's not a dupe! Turns out it's not an issue with the tests at all. It was a bug that hid itself very well and only coincidentally passed tests because of how the used SQLite driver works Ugh, this again. I thought I fixed it last time. Looks like I did not. I'll take care of it. Thanks! I really didn't look at it at all, just dumped it here so I didn't forget about it, apologies if a dup. Actually ran into it twice today. Well, if you encountered it again it's not a dupe! Turns out it's not an issue with the tests at all. It was a bug that hid itself very well and only coincidentally passed tests because of how the used SQLite driver works
2022-11-22T14:24:19
litestar-org/litestar
860
litestar-org__litestar-860
[ "849" ]
388ef137aadced75f09b7a38177cb279cf36f656
diff --git a/starlite/middleware/logging.py b/starlite/middleware/logging.py --- a/starlite/middleware/logging.py +++ b/starlite/middleware/logging.py @@ -103,22 +103,26 @@ async def __call__(self, scope: "Scope", receive: "Receive", send: "Send") -> No if not hasattr(self, "logger"): self.logger = scope["app"].get_logger(self.config.logger_name) self.is_struct_logger = structlog_installed and isinstance(self.logger, BindableLogger) - if self.config.request_log_fields: - await self.log_request(scope=scope) + if self.config.response_log_fields: send = self.create_send_wrapper(scope=scope, send=send) + + if self.config.request_log_fields: + await self.log_request(scope=scope, receive=receive) + await self.app(scope, receive, send) - async def log_request(self, scope: "Scope") -> None: + async def log_request(self, scope: "Scope", receive: "Receive") -> None: """Extract request data and log the message. Args: scope: The ASGI connection scope. + receive: ASGI receive callable Returns: None """ - extracted_data = await self.extract_request_data(request=scope["app"].request_class(scope)) + extracted_data = await self.extract_request_data(request=scope["app"].request_class(scope, receive=receive)) self.log_message(values=extracted_data) def log_response(self, scope: "Scope") -> None:
diff --git a/tests/middleware/test_logging_middleware.py b/tests/middleware/test_logging_middleware.py --- a/tests/middleware/test_logging_middleware.py +++ b/tests/middleware/test_logging_middleware.py @@ -1,10 +1,10 @@ from logging import INFO -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Dict import pytest from structlog.testing import capture_logs -from starlite import Cookie, LoggingConfig, Response, StructLoggingConfig, get +from starlite import Cookie, LoggingConfig, Response, StructLoggingConfig, get, post from starlite.config.compression import CompressionConfig from starlite.config.logging import default_handlers from starlite.middleware import LoggingMiddlewareConfig @@ -143,7 +143,7 @@ def test_logging_middleware_compressed_response_body(include: bool, caplog: "Log with create_test_client( route_handlers=[handler], compression_config=CompressionConfig(backend="gzip", minimum_size=1), - middleware=[LoggingMiddlewareConfig(include_compressed_body=include).middleware], + middleware=[LoggingMiddlewareConfig(include_compressed_body=include, request_log_fields=[]).middleware], ) as client, caplog.at_level(INFO): # Set cookies on the client to avoid warnings about per-request cookies. client.cookies = {"request-cookie": "abc"} # type: ignore @@ -155,3 +155,16 @@ def test_logging_middleware_compressed_response_body(include: bool, caplog: "Log assert "body=" in caplog.messages[1] else: assert "body=" not in caplog.messages[1] + + +def test_logging_middleware_post_body() -> None: + @post("/") + def post_handler(data: Dict[str, str]) -> Dict[str, str]: + return data + + with create_test_client( + route_handlers=[post_handler], middleware=[LoggingMiddlewareConfig().middleware], logging_config=LoggingConfig() + ) as client: + res = client.post("/", json={"foo": "bar"}) + assert res.status_code == 201 + assert res.json() == {"foo": "bar"}
Bug: POSTs Result In HTTP 500 When Logging Middleware Enabled **Describe the bug** With the logging middleware enabled, POSTs are returning an HTTP 500. **To Reproduce** ```python from starlite import Starlite, LoggingConfig, post from starlite.middleware import LoggingMiddlewareConfig from pydantic import BaseModel logging_middleware_config = LoggingMiddlewareConfig() class Widget(BaseModel): name: str description: str | None = None width_inches: float height_inches: float @post("/") async def my_handler(data: Widget) -> Widget: return data app = Starlite( route_handlers=[my_handler], logging_config=LoggingConfig(), middleware=[logging_middleware_config.middleware], ) ``` Start up the app, POST to it: ```shell curl --request POST --url http://localhost:8000/ --header 'Content-Type: application/json' --data '{ "name": "foo", "description": "bar", "width_inches": 1.23, "height_inches": 4.56 }' {"status_code":500,"detail":"RuntimeError()"} ``` If I remove the `middleware` argument from the app and restart, POST works as expected. **Additional context** Python 3.10.8 ``` anyio==3.6.2 appdirs==1.4.4 attrs==22.1.0 bcrypt==4.0.1 beanie==1.15.4 black==22.10.0 casbin==1.17.4 casbin-pymongo-adapter==1.0.0 certifi==2022.9.24 cffi==1.15.1 charset-normalizer==2.1.1 click==8.1.3 commonmark==0.9.1 coverage==6.5.0 cryptography==38.0.3 distlib==0.3.6 dnspython==2.2.1 email-validator==1.3.0 eradicate==2.1.0 exceptiongroup==1.0.4 Faker==15.3.2 filelock==3.8.0 flake8==5.0.4 flake8-black==0.3.4 flake8-builtins==2.0.1 flake8-comprehensions==3.10.1 flake8-eradicate==1.4.0 flake8-isort==5.0.0 flake8-plugin-utils==1.3.2 flake8-pytest-style==1.6.0 ggshield==1.14.1 graphql-core==3.2.3 h11==0.14.0 h2==4.1.0 hpack==4.0.0 httpcore==0.16.1 httpx==0.23.1 hyperframe==6.0.1 idna==3.4 iniconfig==1.1.1 isort==5.10.1 Jinja2==3.1.2 ldap3==2.9.1 MarkupSafe==2.1.1 marshmallow==3.18.0 marshmallow-dataclass==8.5.10 mccabe==0.7.0 mongomock==4.1.2 mongomock-motor==0.0.13 motor==3.1.1 multidict==6.0.2 mypy-extensions==0.4.3 oauthlib==3.2.2 orjson==3.8.2 packaging==21.3 passlib==1.7.4 pathspec==0.10.2 pep8-naming==0.13.2 picologging==0.9.1 platformdirs==2.5.4 pluggy==1.0.0 pyasn1==0.4.8 pycodestyle==2.9.1 pycparser==2.21 pydantic==1.10.2 pydantic-factories==1.15.0 pydantic-openapi-schema==1.3.0 pyflakes==2.5.0 pygitguardian==1.4.0 Pygments==2.13.0 pymongo==4.3.3 pyparsing==3.0.9 pytest==7.2.0 pytest-asyncio==0.20.2 pytest-cov==4.0.0 python-dateutil==2.8.2 python-dotenv==0.21.0 python-multipart==0.0.5 PyYAML==6.0 requests==2.28.1 rfc3986==1.5.0 rich==12.5.1 sentinels==1.0.0 sgqlc==16.0 simpleeval==0.9.12 six==1.16.0 sniffio==1.3.0 starlite==1.40.1 starlite-multipart==1.2.0 toml==0.10.2 tomli==2.0.1 typing-inspect==0.8.0 typing_extensions==4.4.0 urllib3==1.26.12 uvicorn==0.20.0 virtualenv==20.16.7 yarl==1.8.1 ```
I can reproduce the problem. Will take a look into it tonight
2022-11-26T12:05:06
litestar-org/litestar
875
litestar-org__litestar-875
[ "871" ]
0a022a998f3798a959315de2db8785b2540c78f4
diff --git a/starlite/middleware/session/memcached_backend.py b/starlite/middleware/session/memcached_backend.py --- a/starlite/middleware/session/memcached_backend.py +++ b/starlite/middleware/session/memcached_backend.py @@ -63,7 +63,8 @@ async def delete(self, session_id: str) -> None: await self.memcached.delete(self._id_to_storage_key(session_id)) @deprecated( - "1.43.0", info="This functionality is not natively supported by memcached. Use the redis backend instead if you require it." + "1.43.0", + info="This functionality is not natively supported by memcached. Use the redis backend instead if you require it.", ) async def delete_all(self) -> None: # pragma: no cover """Delete all data stored within this backend.
Bug: Structlog example throws a 500 error **Describe the bug** Using the [Structlog sample code](https://starlite-api.github.io/starlite/usage/0-the-starlite-app/4-logging) with Starlite returns a 500 error. **To Reproduce** Paste the exact sample code linked into a text file, run.py. Have the dependencies (below) installed and available. Run the command `uvicorn run:app`. Hit http://localhost:8000 in the browser. Error response: `{"status_code":500,"detail":"TypeError(\"_make_filtering_bound_logger.<locals>.log() missing 1 required positional argument: 'event'\")"}` **Additional context** Python 3.10 Starlite 1.39.0 Structlog 22.3.0 Uvicorn 0.19.0 (extras = standard) MacOS Monterey 12.16.1
~~@robertlagrant could you please try to launch the code with the latest Starlite version.~~ nvm, I wasn't paying attention to the error message. @jtraub same on Starlite 1.42.0 anyway :) @robertlagrant it is just a typo in the docs. Loggers follow [`Logger`](https://github.com/starlite-api/starlite/blob/main/starlite/types/protocols.py#L4) protocol which doesn't have `log` method. So you need to replace ```python request.logger.log("inside a request") ``` in the example code with ```python request.logger.info("inside a request") ``` and it should work. There is an ongoing effort to make sure that all examples in the docs are runnable (#343). @provinzkraut is working hard on this and I think it will be addressed soon. Confirmed - this change works. ```bash % poetry run uvicorn run:app INFO: Started server process [80291] INFO: Waiting for application startup. INFO: Application startup complete. INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) {"event":"inside a request","level":"info","timestamp":"2022-11-28T19:19:25.317728Z"} INFO: 127.0.0.1:62892 - "GET / HTTP/1.1" 200 OK ```
2022-11-29T12:01:07
litestar-org/litestar
902
litestar-org__litestar-902
[ "899", "899" ]
72a5bc35c75134510cc6892f89cecd6ed54bb9cd
diff --git a/starlite/datastructures/provide.py b/starlite/datastructures/provide.py --- a/starlite/datastructures/provide.py +++ b/starlite/datastructures/provide.py @@ -23,7 +23,7 @@ from inspect import Traceback from starlite.signature import SignatureModel - from starlite.types import AnyCallable, AnyGenerator, ASGIApp, Receive, Scope, Send + from starlite.types import AnyCallable, AnyGenerator class Provide: @@ -155,22 +155,6 @@ async def cleanup(self) -> None: for generator in self._generators: task_group.start_soon(self._wrap_next(generator)) - def wrap_asgi(self, app: "ASGIApp") -> "ASGIApp": - """Wrap an ASGI callable such that all generators will be called before it. - - Args: - app: An ASGI callable - - Returns: - An ASGI callable - """ - - async def wrapped(scope: "Scope", receive: "Receive", send: "Send") -> None: - await self.cleanup() - await app(scope, receive, send) - - return wrapped - async def __aenter__(self) -> None: """Support the async contextmanager protocol to allow for easier catching and throwing of exceptions into the generators. diff --git a/starlite/routes/http.py b/starlite/routes/http.py --- a/starlite/routes/http.py +++ b/starlite/routes/http.py @@ -163,10 +163,11 @@ async def _call_handler_function( plugins=request.app.plugins, request=request, ) + if cleanup_group: - return cleanup_group.wrap_asgi(response) + await cleanup_group.cleanup() - return response + return response # noqa: R504 @staticmethod async def _get_response_data(
diff --git a/tests/kwargs/test_generator_dependencies.py b/tests/kwargs/test_generator_dependencies.py --- a/tests/kwargs/test_generator_dependencies.py +++ b/tests/kwargs/test_generator_dependencies.py @@ -54,8 +54,10 @@ async def dependency() -> AsyncGenerator[str, None]: return dependency [email protected]("cache", [False, True]) @pytest.mark.parametrize("dependency_fixture", ["generator_dependency", "async_generator_dependency"]) def test_generator_dependency( + cache: bool, request: FixtureRequest, dependency_fixture: str, cleanup_mock: MagicMock, @@ -64,7 +66,7 @@ def test_generator_dependency( ) -> None: dependency = request.getfixturevalue(dependency_fixture) - @get("/", dependencies={"dep": Provide(dependency)}) + @get("/", dependencies={"dep": Provide(dependency)}, cache=cache) def handler(dep: str) -> Dict[str, str]: return {"value": dep}
Bug: Caching response throws AttributeError on GET: Can't pickle local object 'DependencyCleanupGroup.wrap_asgi.<locals>.wrapped' **Describe the bug** When caching the response of a get request for a `Template`, I get the following exception which throws a server 500 error: `AttributeError on GET: Can't pickle local object 'DependencyCleanupGroup.wrap_asgi.<locals>.wrapped'` **To Reproduce** Here is a reproducible example: ``` import uvicorn from starlite import Starlite, get, Request, State, Template, Controller, TemplateConfig from starlite.template.jinja import JinjaTemplateEngine class FrontEnd(Controller): @get("/", cache=60) async def serveHomepage(self, request: Request, state: State) -> Template: return Template( name="homepage.html.j2", context={"request": request}, ) @get("/hello-world", cache=60) async def hello_world(self) -> dict[str, str]: """Handler function that returns a greeting dictionary.""" return {"hello": "world"} app = Starlite( route_handlers=[FrontEnd], template_config=TemplateConfig( directory="src/templates", engine=JinjaTemplateEngine ), debug=True, ) if __name__ == "__main__": uvicorn.run(app, host="127.0.0.1", port=8000) ``` You can use this for the Jinja template: ``` <html> <head> </head> <body> <h1>Homepage Header</h1> </body> </html> ``` **Additional context** If you remove the cache value from the `Template` route (or set it to zero), the `get` requests are served as expected. In the example code, I also included a route for a non-template request, `/hello-world`, which does not throw an error. So the problem seems to lie with `Template` responses, or some subset of responses. Bug: Caching response throws AttributeError on GET: Can't pickle local object 'DependencyCleanupGroup.wrap_asgi.<locals>.wrapped' **Describe the bug** When caching the response of a get request for a `Template`, I get the following exception which throws a server 500 error: `AttributeError on GET: Can't pickle local object 'DependencyCleanupGroup.wrap_asgi.<locals>.wrapped'` **To Reproduce** Here is a reproducible example: ``` import uvicorn from starlite import Starlite, get, Request, State, Template, Controller, TemplateConfig from starlite.template.jinja import JinjaTemplateEngine class FrontEnd(Controller): @get("/", cache=60) async def serveHomepage(self, request: Request, state: State) -> Template: return Template( name="homepage.html.j2", context={"request": request}, ) @get("/hello-world", cache=60) async def hello_world(self) -> dict[str, str]: """Handler function that returns a greeting dictionary.""" return {"hello": "world"} app = Starlite( route_handlers=[FrontEnd], template_config=TemplateConfig( directory="src/templates", engine=JinjaTemplateEngine ), debug=True, ) if __name__ == "__main__": uvicorn.run(app, host="127.0.0.1", port=8000) ``` You can use this for the Jinja template: ``` <html> <head> </head> <body> <h1>Homepage Header</h1> </body> </html> ``` **Additional context** If you remove the cache value from the `Template` route (or set it to zero), the `get` requests are served as expected. In the example code, I also included a route for a non-template request, `/hello-world`, which does not throw an error. So the problem seems to lie with `Template` responses, or some subset of responses.
Attaching traceback: ![image](https://user-images.githubusercontent.com/114229148/205334660-bd1f2208-1824-498b-b8d7-2444771fa3ad.png) Have you switched python versions recently? Nope, I’ve been on 3.11 since the day it came out @Goldziher I think it has nothing to do with the Python version. The offending code is the fact that now response is wrapped into DependencyCleanupGroup to be able to do cleanup - [here](https://github.com/starlite-api/starlite/blob/main/starlite/routes/http.py#L167) Obviously this can not be cached and before saving response to cache we need to unwrap it first. @jtraub You're right. `DependencyCleaupGroup` essentially creates an ASGI middleware here. The reasoning so we don't have to pass the cleanup group all the way up to where the response is returned, which we need to we can consistently call the cleanup immediately before the response is returned. I'm thinking of either making a transparent wrapper so it can be unwrapped if needed, or forego the wrapping and simply accept that we have to pass it around a bit. WDYT? @provinzkraut I am a bit torn here because having nice and pure "ASGIApp" typings makes me happy but on the other hand we might forget to unwrap it again somewhere else. However, it seems like making a transparent wrapper with a way to access original response object is a bit better. We can do both I think. The wrapper can be made into an ASGI callable that can be pickled. After thinking about this, the proper way to do this seems to be calling the cleanup **before** the response is cached. This would also mean we can omit passing the cleanup group around. Attaching traceback: ![image](https://user-images.githubusercontent.com/114229148/205334660-bd1f2208-1824-498b-b8d7-2444771fa3ad.png) Have you switched python versions recently? Nope, I’ve been on 3.11 since the day it came out @Goldziher I think it has nothing to do with the Python version. The offending code is the fact that now response is wrapped into DependencyCleanupGroup to be able to do cleanup - [here](https://github.com/starlite-api/starlite/blob/main/starlite/routes/http.py#L167) Obviously this can not be cached and before saving response to cache we need to unwrap it first. @jtraub You're right. `DependencyCleaupGroup` essentially creates an ASGI middleware here. The reasoning so we don't have to pass the cleanup group all the way up to where the response is returned, which we need to we can consistently call the cleanup immediately before the response is returned. I'm thinking of either making a transparent wrapper so it can be unwrapped if needed, or forego the wrapping and simply accept that we have to pass it around a bit. WDYT? @provinzkraut I am a bit torn here because having nice and pure "ASGIApp" typings makes me happy but on the other hand we might forget to unwrap it again somewhere else. However, it seems like making a transparent wrapper with a way to access original response object is a bit better. We can do both I think. The wrapper can be made into an ASGI callable that can be pickled. After thinking about this, the proper way to do this seems to be calling the cleanup **before** the response is cached. This would also mean we can omit passing the cleanup group around.
2022-12-03T12:38:19
litestar-org/litestar
992
litestar-org__litestar-992
[ "988" ]
5e5e145a4e7b79eb6e124ef48fa8db266827a048
diff --git a/starlite/middleware/session/__init__.py b/starlite/middleware/session/__init__.py --- a/starlite/middleware/session/__init__.py +++ b/starlite/middleware/session/__init__.py @@ -1,9 +1,27 @@ +from typing import Any + +from starlite.utils import warn_deprecation + from .base import SessionMiddleware -from .cookie_backend import ( - CookieBackendConfig as SessionCookieConfig, # backwards compatible export -) - -__all__ = [ - "SessionMiddleware", - "SessionCookieConfig", -] + + +def __getattr__(name: str) -> Any: + """Provide lazy importing as per https://peps.python.org/pep-0562/""" + + if name != "SessionCookieConfig": + raise AttributeError(f"Module {__package__} has no attribute {name}") + + from .cookie_backend import CookieBackendConfig + + warn_deprecation( + deprecated_name=f"{name} from {__package__}", + kind="import", + alternative="'from startlite.middleware.sessions.cookie_backend import CookieBackendConfig'", + version="1.47.0", + ) + + globals()[name] = CookieBackendConfig + return CookieBackendConfig + + +__all__ = ["SessionMiddleware"]
Bug: Running `starlite run` after installing starlite[cli] gives error about missing cryptography package The error is here: ``` Traceback (most recent call last): File "C:\Users\hanne\Documents\Programme\analyze-wiktionary\.venv\lib\site-packages\starlite\middleware\session\cookie_backend.py", line 20, in <module> from cryptography.exceptions import InvalidTag ModuleNotFoundError: No module named 'cryptography' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Python310\lib\runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Python310\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "C:\Users\hanne\Documents\Programme\analyze-wiktionary\.venv\Scripts\starlite.exe\__main__.py", line 4, in <module> File "C:\Users\hanne\Documents\Programme\analyze-wiktionary\.venv\lib\site-packages\starlite\cli.py", line 41, in <module> from starlite.middleware.session import SessionMiddleware File "C:\Users\hanne\Documents\Programme\analyze-wiktionary\.venv\lib\site-packages\starlite\middleware\session\__init__.py", line 2, in <module> from .cookie_backend import ( File "C:\Users\hanne\Documents\Programme\analyze-wiktionary\.venv\lib\site-packages\starlite\middleware\session\cookie_backend.py", line 23, in <module> raise MissingDependencyException("cryptography is not installed") from e starlite.exceptions.base_exceptions.MissingDependencyException: cryptography is not installed ``` I thought it might be a good idea to install the package automatically with the CLI extra. (Or to update the [docs](https://starlite-api.github.io/starlite/usage/19-cli/?h=uvicorn) if I'm missing something). My versions: Windows, Python 3.10, starlite 1.46.0 PS: Thank you all for the great amount of effort you spend on this project!
Adding to this, when installing `starlite[standard]`, rich and click are not installed, because Poetry doesn't support referencing the other definitions in the extras section: https://github.com/python-poetry/poetry/issues/5471. > I thought it might be a good idea to install the package automatically with the CLI extra No, it's not actually required by the CLI. The CLI is just using a wrong import (that's on me) that should have been properly marked as deprecated (also on me :upside_down_face:). I'll fix that and make it proper.
2022-12-26T09:39:05
litestar-org/litestar
1,000
litestar-org__litestar-1000
[ "999" ]
55eea965b2ac9e56aca77797512ab878b0b7499b
diff --git a/starlite/openapi/controller.py b/starlite/openapi/controller.py --- a/starlite/openapi/controller.py +++ b/starlite/openapi/controller.py @@ -303,7 +303,7 @@ def render_swagger_ui(self, request: Request) -> str: """ schema = self.get_schema_from_request(request) # Note: Fix for Swagger rejection OpenAPI >=3.1 - if not self._dumped_schema: + if not self._dumped_modified_schema: schema_copy = schema.copy() schema_copy.openapi = "3.0.3"
diff --git a/tests/openapi/test_controller.py b/tests/openapi/test_controller.py --- a/tests/openapi/test_controller.py +++ b/tests/openapi/test_controller.py @@ -153,6 +153,21 @@ def test_openapi_swagger(root_path: str) -> None: assert response.headers["content-type"].startswith(MediaType.HTML.value) [email protected]("root_path", root_paths) +def test_openapi_swagger_caching_schema(root_path: str) -> None: + with create_test_client( + [PersonController, PetController], openapi_config=DEFAULT_OPENAPI_CONFIG, root_path=root_path + ) as client: + # Make sure that the schema is tweaked for swagger as the openapi version is changed. + # Because schema can get cached, make sure that getting a different schema type before works. + client.get("/schema/redoc") # Cache the schema + response = client.get("/schema/swagger") # Request swagger, should use a different cache + + assert "3.0.3" in response.text # Make sure the injected version is still there + assert response.status_code == HTTP_200_OK + assert response.headers["content-type"].startswith(MediaType.HTML.value) + + @pytest.mark.parametrize("root_path", root_paths) def test_openapi_stoplight_elements(root_path: str) -> None: with create_test_client(
Bug: Viewing default schema then swagger schema results in error **Describe the bug** Viewing the standard `/schema` route and then viewing `/schema/swagger` results in an empty page. The console log on the swagger route mentions parsing invalid JSON (Trying to parse nothing - `JSON.parse()`) I believe the problem is the caching located [here](https://github.com/starlite-api/starlite/blob/55eea965b2ac9e56aca77797512ab878b0b7499b/starlite/openapi/controller.py#L306). It should be checking for `self._dumped_modified_schema`. Changing to this seems to fix it. **To Reproduce** Run the hello world example from the documentation: ```python from typing import Dict from starlite import Starlite, get @get("/") def hello_world() -> Dict[str, str]: """Handler function that returns a greeting dictionary.""" return {"hello": "world"} app = Starlite(route_handlers=[hello_world]) ``` Then visit `/schema` and the page should be fine. Then visit `/schema/swagger` and it should be an empty page. **Additional context** Add any other context about the problem here.
2022-12-28T23:45:30
litestar-org/litestar
1,005
litestar-org__litestar-1005
[ "1004" ]
b1ddb0e6f37c855774da2fc82dedb8de26252306
diff --git a/starlite/openapi/path_item.py b/starlite/openapi/path_item.py --- a/starlite/openapi/path_item.py +++ b/starlite/openapi/path_item.py @@ -56,7 +56,7 @@ def extract_layered_values( tags.extend(layer.tags) if layer.security: security.extend(layer.security) - return list(set(tags)) if tags else None, security or None + return sorted(set(tags)) if tags else None, security or None def create_path_item(
diff --git a/tests/openapi/test_tags.py b/tests/openapi/test_tags.py --- a/tests/openapi/test_tags.py +++ b/tests/openapi/test_tags.py @@ -23,7 +23,7 @@ class _Controller(Controller): path = "/controller" tags = ["controller"] - @get(tags=["handler"]) + @get(tags=["handler", "a"]) def _handler(self) -> Any: ... @@ -50,8 +50,8 @@ def test_openapi_schema_handler_tags(openapi_schema: "OpenAPI") -> None: def test_openapi_schema_controller_tags(openapi_schema: "OpenAPI") -> None: - assert set(openapi_schema.paths["/controller"].get.tags) == {"handler", "controller"} # type: ignore + assert openapi_schema.paths["/controller"].get.tags == ["a", "controller", "handler"] # type: ignore def test_openapi_schema_router_tags(openapi_schema: "OpenAPI") -> None: - assert set(openapi_schema.paths["/router/controller"].get.tags) == {"handler", "controller", "router"} # type: ignore + assert openapi_schema.paths["/router/controller"].get.tags == ["a", "controller", "handler", "router"] # type: ignore
Bug: openapi render for multiple tags isn't consistent **Describe the bug** When the openapi renders tags from both a controller and a route it is not deterministic. This may not be a bug? But it surprised me so thought I'd raise it. I'm unsure if I'm doing something crazy but for a project, we check in the generated json openapi schema so we can browse the API live in gitlab. I've recently added a tag to both a controller and a route in it. But because the order of the tags isn't consistent they are going to keep flip flopping as we have a pre-commit that generates the json to make sure it's up to date. I hope that ramble makes sense... **To Reproduce** ```python from typing import Dict from starlite import Starlite, Controller, get class TestController(Controller): tags = ["a"] @get("/", tags=["b"]) def hello_world(self) -> Dict[str, str]: """Handler function that returns a greeting dictionary.""" return {"hello": "world"} app = Starlite(route_handlers=[TestController]) print(app.openapi_schema.paths["/"].get.tags) ``` If you run that multiple times, you will see you get either: ```python ['a', 'b'] ``` or ```python ['b', 'a'] ``` **Additional context** I believe the problem is [here](https://github.com/starlite-api/starlite/blob/835749112e8364c1516f45973c924774aca22ca9/starlite/openapi/path_item.py#L59) as it forces construction of a new set. Sorting them before returning would be viable as there shouldn't be _too many_ tags and it's a one time thing I believe? But as I said, it may not be a problem you care about as I could be doing something silly.
Let me know if this is correct and an okay approach and I'll make a PR with a test So the issue is the order of tags? I'd assume we probably use a set somewhere, which will jumble the order. Yup 🙂 > I believe the problem is [here](https://github.com/starlite-api/starlite/blob/835749112e8364c1516f45973c924774aca22ca9/starlite/openapi/path_item.py#L59) as it forces construction of a new set. Sorting them before returning would be viable as there shouldn't be too many tags and it's a one time thing I believe? > Yup 🙂 > > > I believe the problem is [here](https://github.com/starlite-api/starlite/blob/835749112e8364c1516f45973c924774aca22ca9/starlite/openapi/path_item.py#L59) as it forces construction of a new set. Sorting them before returning would be viable as there shouldn't be too many tags and it's a one time thing I believe? Sure. Wanna add a PR? Yeah, can do. I was just wondering if you do try to guarantee the repeatability of your schema generation from the same code - There may well be other places > if you do try to guarantee the repeatability of your schema generation from the same code Afaik we currently don't have a strong guarantee for this, but imo it makes sense as a requirement. The schema should not change if the code doesn't change.
2022-12-29T16:32:25
litestar-org/litestar
1,009
litestar-org__litestar-1009
[ "1008" ]
33c8aea65a1493c63f3942ef0c3751f6a455bf74
diff --git a/starlite/utils/serialization.py b/starlite/utils/serialization.py --- a/starlite/utils/serialization.py +++ b/starlite/utils/serialization.py @@ -93,19 +93,19 @@ def dec_hook(type_: Any, value: Any) -> Any: # pragma: no cover _msgspec_msgpack_decoder = msgspec.msgpack.Decoder(dec_hook=dec_hook) -def encode_json(obj: Any, enc_hook: Optional[Callable[[Any], Any]] = default_serializer) -> bytes: +def encode_json(obj: Any, default: Optional[Callable[[Any], Any]] = default_serializer) -> bytes: """Encode a value into JSON. Args: obj: Value to encode - enc_hook: Optional callable to support non-natively supported types + default: Optional callable to support non-natively supported types. Returns: JSON as bytes """ - if enc_hook is None or enc_hook is default_serializer: + if default is None or default is default_serializer: return _msgspec_json_encoder.encode(obj) - return msgspec.json.encode(obj, enc_hook=enc_hook) + return msgspec.json.encode(obj, enc_hook=default) def decode_json(raw: Union[str, bytes]) -> Any:
diff --git a/tests/logging_config/test_structlog_config.py b/tests/logging_config/test_structlog_config.py --- a/tests/logging_config/test_structlog_config.py +++ b/tests/logging_config/test_structlog_config.py @@ -1,32 +1,43 @@ +from pytest import CaptureFixture # noqa: TC002 from structlog.processors import JSONRenderer -from structlog.testing import capture_logs from structlog.types import BindableLogger from starlite.config import StructLoggingConfig from starlite.testing import create_test_client +from starlite.utils.serialization import decode_json, encode_json +# structlog.testing.capture_logs changes the processors +# Because we want to test processors, use capsys instead -def test_structlog_config() -> None: - with create_test_client([], logging_config=StructLoggingConfig()) as client, capture_logs() as cap_logs: + +def test_structlog_config_default(capsys: CaptureFixture) -> None: + with create_test_client([], logging_config=StructLoggingConfig()) as client: assert client.app.logger assert isinstance(client.app.logger, BindableLogger) client.app.logger.info("message", key="value") - assert len(cap_logs) == 1 - assert cap_logs[0] == {"key": "value", "event": "message", "log_level": "info"} + + log_messages = [decode_json(x) for x in capsys.readouterr().out.splitlines()] + assert len(log_messages) == 1 + + # Format should be: {event: message, key: value, level: info, timestamp: isoformat} + log_messages[0].pop("timestamp") # Assume structlog formats timestamp correctly + assert log_messages[0] == {"event": "message", "key": "value", "level": "info"} -def test_structlog_config_specify_processors() -> None: - logging_config = StructLoggingConfig(processors=[JSONRenderer()]) +def test_structlog_config_specify_processors(capsys: CaptureFixture) -> None: + logging_config = StructLoggingConfig(processors=[JSONRenderer(encode_json)]) - with create_test_client([], logging_config=logging_config) as client, capture_logs() as cap_logs: + with create_test_client([], logging_config=logging_config) as client: assert client.app.logger assert isinstance(client.app.logger, BindableLogger) client.app.logger.info("message1", key="value1") - assert len(cap_logs) == 1 - assert cap_logs[0] == {"key": "value1", "event": "message1", "log_level": "info"} - # Log twice to make sure issue #882 doesn't appear again client.app.logger.info("message2", key="value2") - assert len(cap_logs) == 2 - assert cap_logs[1] == {"key": "value2", "event": "message2", "log_level": "info"} + + log_messages = [decode_json(x) for x in capsys.readouterr().out.splitlines()] + + assert log_messages == [ + {"key": "value1", "event": "message1"}, + {"key": "value2", "event": "message2"}, + ]
Bug: Structlog example no longer works Me again. Sorry 🙈 **Describe the bug** Running the structlog example [here](https://starlite-api.github.io/starlite/1.48/usage/0-the-starlite-app/?h=structlog#using-structlog) results in an internal server error as of v1.45 (I think) ``` {"status_code":500,"detail":"TypeError(\"encode_json() got an unexpected keyword argument 'default'\")"} ``` The default encoder was changed [here](https://github.com/starlite-api/starlite/pull/891/files#diff-6b2294023eb60948cd9f742e4930255a72254daf74f9e3157df8d479a685b123R213) Which doesn't accept the `default` argument given [here](https://github.com/hynek/structlog/blob/main/src/structlog/processors.py#L318) I'm not sure if it's a structlog problem or a starlite problem. Maybe the solution is to rename `enc_hook` to `default` then it mirrors the signature of `json.dumps`? I'm not sure, to be honest. **To Reproduce** Run the structlog example in the documentation: ```python from starlite import Starlite, StructLoggingConfig, Request, get @get("/") def my_router_handler(request: Request) -> None: request.logger.info("inside a request") return None logging_config = StructLoggingConfig() app = Starlite(route_handlers=[my_router_handler], logging_config=logging_config) ``` **Additional context** Add any other context about the problem here.
> Me again. Sorry :see_no_evil: Don't be, every bug report is very welcome! > Maybe the solution is to rename `enc_hook` to `default` then it mirrors the signature of json.dumps Yes, that would be the best solution. Wanna add a PR? This also definitely should have been caught by our tests.
2022-12-30T13:40:23
litestar-org/litestar
1,011
litestar-org__litestar-1011
[ "1003" ]
e6a7aefefda14301c748db59992cbe3b7f5279e2
diff --git a/starlite/utils/serialization.py b/starlite/utils/serialization.py --- a/starlite/utils/serialization.py +++ b/starlite/utils/serialization.py @@ -1,27 +1,30 @@ +from collections import deque +from decimal import Decimal +from ipaddress import ( + IPv4Address, + IPv4Interface, + IPv4Network, + IPv6Address, + IPv6Interface, + IPv6Network, +) from pathlib import PurePosixPath +from re import Pattern from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Union import msgspec from pydantic import ( - AnyUrl, BaseModel, ByteSize, ConstrainedBytes, ConstrainedDate, ConstrainedDecimal, - ConstrainedFloat, - ConstrainedFrozenSet, - ConstrainedInt, - ConstrainedList, - ConstrainedSet, - ConstrainedStr, - EmailStr, NameEmail, - PaymentCardNumber, SecretField, StrictBool, ) from pydantic.color import Color +from pydantic.json import decimal_encoder if TYPE_CHECKING: from starlite.types import TypeEncodersMap @@ -31,22 +34,36 @@ # pydantic specific types BaseModel: lambda m: m.dict(), ByteSize: lambda b: b.real, - EmailStr: str, NameEmail: str, Color: str, - AnyUrl: str, SecretField: str, - ConstrainedInt: int, - ConstrainedFloat: float, - ConstrainedStr: str, ConstrainedBytes: lambda b: b.decode("utf-8"), - ConstrainedList: list, - ConstrainedSet: set, - ConstrainedFrozenSet: frozenset, ConstrainedDecimal: float, ConstrainedDate: lambda d: d.isoformat(), - PaymentCardNumber: str, - StrictBool: int, # pydantic compatibility + IPv4Address: str, + IPv4Interface: str, + IPv4Network: str, + IPv6Address: str, + IPv6Interface: str, + IPv6Network: str, + # pydantic compatibility + deque: list, + Decimal: decimal_encoder, + StrictBool: int, + Pattern: lambda o: o.pattern, + # support subclasses of stdlib types, e.g. pydantic's constrained types. If no + # previous type matched, these will be the last type in the mro, so we use this to + # (attempt to) convert a subclass into its base class. + # see https://github.com/jcrist/msgspec/issues/248 + # and https://github.com/starlite-api/starlite/issues/1003 + str: str, + int: int, + float: float, + list: list, + tuple: tuple, + set: set, + frozenset: frozenset, + dict: dict, }
diff --git a/tests/utils/test_serialization.py b/tests/utils/test_serialization.py --- a/tests/utils/test_serialization.py +++ b/tests/utils/test_serialization.py @@ -35,6 +35,34 @@ person = PersonFactory.build() +class CustomStr(str): + pass + + +class CustomInt(int): + pass + + +class CustomFloat(float): + pass + + +class CustomList(list): + pass + + +class CustomSet(set): + pass + + +class CustomFrozenSet(frozenset): + pass + + +class CustomTuple(tuple): + pass + + class Model(BaseModel): path: PosixPath = PosixPath("example") @@ -62,6 +90,14 @@ class Model(BaseModel): strict_bytes: StrictBytes = StrictBytes(b"hello") strict_bool: StrictBool = StrictBool(True) + custom_str: CustomStr = CustomStr() + custom_int: CustomInt = CustomInt() + custom_float: CustomFloat = CustomFloat() + custom_list: CustomList = CustomList() + custom_set: CustomSet = CustomSet() + custom_frozenset: CustomFrozenSet = CustomFrozenSet() + custom_tuple: CustomTuple = CustomTuple() + model = Model() @@ -90,6 +126,13 @@ class Model(BaseModel): (model.strict_bytes, "hello"), (model.strict_bool, 1), (model, model.dict()), + (model.custom_str, ""), + (model.custom_int, 0), + (model.custom_float, 0.0), + (model.custom_list, []), + (model.custom_set, set()), + (model.custom_frozenset, frozenset()), + (model.custom_tuple, ()), ], ) def test_default_serializer(value: Any, expected: Any) -> None:
Bug: Custom data types with validators cannot be serialized since 1.45 **Describe the bug** Since version 1.45 custom data types with pydantic validators cannot be serialized anymore. Deserialization works fine. **To Reproduce** Example app that works in 1.44, but doesn't in 1.45+: Note that the print gets executed. ```python from pydantic import BaseModel from starlite import Starlite, post, Request, Response, LoggingConfig from starlite.utils import create_exception_response class CustomType(str): @classmethod def __get_validators__(cls): yield cls.get_validators_must_yield_something_so_here_we_are @classmethod def get_validators_must_yield_something_so_here_we_are(cls, value): return cls(value) class Model(BaseModel): foo: CustomType @post('/foo') def foo(data: Model) -> Model: print(data) return data def logging_exception_handler(request: Request, exc: Exception) -> Response: request.logger.error("Application Exception", exc_info = exc) return create_exception_response(exc) app = Starlite( [foo], logging_config = LoggingConfig(), exception_handlers={Exception: logging_exception_handler}, ) ``` **Additional context** This is the stacktrace that I got with the example above: ``` Traceback (most recent call last): File ".../python3.11/site-packages/starlite/response/base.py", line 216, in render return encode_json(content, self.serializer) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File ".../python3.11/site-packages/starlite/utils/serialization.py", line 59, in encode_json return _msgspec_json_encoder.encode(obj) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File ".../python3.11/site-packages/starlite/utils/serialization.py", line 24, in default_serializer raise TypeError(f"Unsupported type: {type(value)!r}") TypeError: Unsupported type: <class 'app2.CustomType'> The above exception was the direct cause of the following exception: Traceback (most recent call last): File ".../python3.11/site-packages/starlite/middleware/exceptions/middleware.py", line 47, in __call__ await self.app(scope, receive, send) File ".../python3.11/site-packages/starlite/routes/http.py", line 75, in handle response = await self._get_response_for_request( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File ".../python3.11/site-packages/starlite/routes/http.py", line 127, in _get_response_for_request response = await self._call_handler_function( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File ".../python3.11/site-packages/starlite/routes/http.py", line 163, in _call_handler_function else await route_handler.to_response( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File ".../python3.11/site-packages/starlite/handlers/http.py", line 606, in to_response return await response_handler(app=app, data=data, plugins=plugins, request=request) # type: ignore ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File ".../python3.11/site-packages/starlite/handlers/http.py", line 203, in handler response = response_class( ^^^^^^^^^^^^^^^ File ".../python3.11/site-packages/starlite/response/base.py", line 109, in __init__ self.body = content if isinstance(content, bytes) else self.render(content) ^^^^^^^^^^^^^^^^^^^^ File ".../python3.11/site-packages/starlite/response/base.py", line 218, in render raise ImproperlyConfiguredException("Unable to serialize response content") from e starlite.exceptions.http_exceptions.ImproperlyConfiguredException: 500: Unable to serialize response content ```
Okay so, this is not a bug but expected behaviour. It's really a limitation of Pydantic, since it doesn't normalise custom Pydantic-types when calling `BaseModel.dict`. Providing a method to convert Pydantic models to stdlib types (as `BaseModel.json()` does internally) has been a long requested feature, but afaict, it's not something that's going to land soon. The workaround for this is to add a type encoder for your custom types. We just added a new feature to make this process easier, so if you're on `main` you can just do: ```python from pydantic import BaseModel from starlite import Starlite, TestClient, post class CustomType(str): @classmethod def __get_validators__(cls): yield cls.get_validators_must_yield_something_so_here_we_are @classmethod def get_validators_must_yield_something_so_here_we_are(cls, value): return cls(value) class Model(BaseModel): foo: CustomType @post("/foo") def foo(data: Model) -> Model: return data app = Starlite([foo], type_encoders={CustomType: str}) with TestClient(app=app) as client: res = client.post("/foo", json={"foo": "bar"}) print(res.json()) ``` <details> <summary>For previous Starlite versions, you need to create a custom response class</summary> ```python from pydantic import BaseModel from starlite import Starlite, TestClient, post, Response class CustomType(str): @classmethod def __get_validators__(cls): yield cls.get_validators_must_yield_something_so_here_we_are @classmethod def get_validators_must_yield_something_so_here_we_are(cls, value): return cls(value) class Model(BaseModel): foo: CustomType @post("/foo") def foo(data: Model) -> Model: return data class MyResponse(Response): type_encoders = {CustomType: str} app = Starlite([foo], response_class=MyResponse) with TestClient(app=app) as client: res = client.post("/foo", json={"foo": "bar"}) print(res.json()) ``` </details> Although I think we could at least support this use case of subclassing stdlib types, as long as they're "backwards compatible", i.e a subclass `CustomType` of `str` can be turned into a native `str` by calling `str(CustomType)`. Thanks for the workarounds. Would appreciate if this was supported out of the box, because I use these custom types quite often. > It's really a limitation of Pydantic, since it doesn't normalise custom Pydantic-types when calling `BaseModel.dict`. Providing a method to convert Pydantic models to stdlib types (as `BaseModel.json()` does internally) has been a long requested feature, but afaict, it's not something that's going to land soon. This is unfortunate. Another option would be to modify the `enc_hook` used by `starlite` to call `json` (and wrap the result in [`msgspec.Raw`](https://jcristharif.com/msgspec/usage.html#raw)) instead of `dict`. This would likely have some performance cost, but pydantic already has a performance cost so :shrug:. I think the diff would be to change https://github.com/starlite-api/starlite/blob/d26f6f637d09294cafd0f695135dc87b9b5cfdd9/starlite/utils/serialization.py#L32 to ```python BaseModel: lambda m: msgspec.Raw(m.json().encode("utf-8")), This is actually a good idea! I think it might come with a significant decrease though, since this will use the standard library's `json` module. It’s possible to swap this out on the model, but it has to be done via the `Config` class. Maybe we can do some patching magic there. I’ll do some test and benchmarks on this. I just created #1006 which would fix my current issue, but won't work for more complex types like datetime. I have a fix coming up that would work for all customised types like yours, as mentioned. But I’d rather evaluate @jcrist's suggestion and then decide which way to go with this. A fix that only works for some types isn’t a good solution in my opinion, since that will cause unexpected behaviour in many places and we’d need to document very explicitly which types are and aren’t supported. @ottermata @jcrist I think this may actually a bug (or undocumented expected behaviour?) in `msgspec`, as *some* subclasses of supported types can be encoded but not all, and `msgspec` deviates from other json implementations (stdlib, orjson, ujson) in this case. I opened an issue at msgspec for this: https://github.com/jcrist/msgspec/issues/248 @jcrist the performance drop is indeed significant: <img src="https://user-images.githubusercontent.com/25355197/210065014-f0325d77-cf07-48d7-8579-56d3074ca725.png" width="500"> > @jcrist the performance drop is indeed significant: > ![rps_serialization](https://user-images.githubusercontent.com/25355197/210065014-f0325d77-cf07-48d7-8579-56d3074ca725.png) > Ouch. > the performance drop is indeed significant: This is with the diff I posted alone? So it's basically comparing starlite w/ `msgspec` (blue) vs the standard library `json` (red), with the overhead of `pydantic` object traversal & conversion (`dict`/`json`) in both cases? Is there any way a call to `.json` can be made to use a different `json.dumps` function at the call site (e..g `obj.json(dumps=msgspec.json.encode)`), rather than configuring it on the pydantic class? > This is with the diff I posted alone? Yup, that's the only change. > Is there any way a call to .json can be made to use a different json.dumps function at the call site (e..g obj.json(dumps=msgspec.json.encode)), rather than configuring it on the pydantic class? Unfortunately not. The only way of using this I see would be to do some introspection on our side, advising users to configure their base model to use `msgspec` for serialization. Adding to this, it's not actually `BaseModel.json()` that supports these custom types, but the stdlib `json`. We are still significantly faster than FastAPI though: <img src="https://user-images.githubusercontent.com/25355197/210083320-1e849c9e-5e8e-49ef-ac7b-1ea989186ec5.png" width="500"> I'm not really sure what's the best way moving forward is here.
2022-12-30T16:32:53
litestar-org/litestar
1,038
litestar-org__litestar-1038
[ "1031" ]
bba0ebf7bc9f27be3e30571dceeecf3c089abc36
diff --git a/starlite/cli.py b/starlite/cli.py --- a/starlite/cli.py +++ b/starlite/cli.py @@ -1,4 +1,5 @@ import importlib +import importlib.util import inspect import sys from dataclasses import dataclass @@ -80,6 +81,7 @@ class StarliteEnv: app_path: str debug: bool app: Starlite + cwd: Path host: Optional[str] = None port: Optional[int] = None reload: Optional[bool] = None @@ -91,6 +93,11 @@ def from_env(cls, app_path: Optional[str]) -> "StarliteEnv": If `python-dotenv` is installed, use it to populate environment first """ + cwd = Path().cwd() + cwd_str_path = str(cwd) + if cwd_str_path not in sys.path: + sys.path.append(cwd_str_path) + try: import dotenv @@ -99,7 +106,7 @@ def from_env(cls, app_path: Optional[str]) -> "StarliteEnv": pass if not app_path: - loaded_app = _autodiscover_app(getenv("STARLITE_APP")) + loaded_app = _autodiscover_app(getenv("STARLITE_APP"), cwd) else: loaded_app = _load_app_from_path(app_path) @@ -113,6 +120,7 @@ def from_env(cls, app_path: Optional[str]) -> "StarliteEnv": port=int(port) if port else None, reload=_bool_from_env("STARLITE_RELOAD"), is_app_factory=loaded_app.is_factory, + cwd=cwd, ) @@ -204,12 +212,11 @@ def _path_to_dotted_path(path: Path) -> str: return ".".join(path.with_suffix("").parts) -def _autodiscover_app(app_path: Optional[str]) -> LoadedApp: +def _autodiscover_app(app_path: Optional[str], cwd: Path) -> LoadedApp: if app_path: console.print(f"Using Starlite app from env: [bright_blue]{app_path!r}") return _load_app_from_path(app_path) - cwd = Path().cwd() for name in AUTODISCOVER_PATHS: path = cwd / name if not path.exists():
diff --git a/tests/test_cli.py b/tests/test_cli.py --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1,9 +1,8 @@ import importlib import shutil import sys -from contextlib import contextmanager from pathlib import Path -from typing import Callable, Generator, List, Optional, Union +from typing import Callable, Generator, List, Optional, Protocol, Union from unittest.mock import MagicMock import pytest @@ -28,21 +27,6 @@ from starlite.middleware.rate_limit import RateLimitConfig from starlite.middleware.session.memory_backend import MemoryBackendConfig - [email protected] -def patch_autodiscovery_paths(request: FixtureRequest) -> Callable[[List[str]], None]: - def patcher(paths: List[str]) -> None: - old_paths = starlite.cli.AUTODISCOVER_PATHS[::] - starlite.cli.AUTODISCOVER_PATHS[:] = paths - - def finalizer() -> None: - starlite.cli.AUTODISCOVER_PATHS[:] = old_paths - - request.addfinalizer(finalizer) - - return patcher - - APP_FILE_CONTENT = """ from starlite import Starlite app = Starlite([]) @@ -72,31 +56,68 @@ def any_name() -> "Starlite": """ -@contextmanager [email protected] +def patch_autodiscovery_paths(request: FixtureRequest) -> Callable[[List[str]], None]: + def patcher(paths: List[str]) -> None: + old_paths = starlite.cli.AUTODISCOVER_PATHS[::] + starlite.cli.AUTODISCOVER_PATHS[:] = paths + + def finalizer() -> None: + starlite.cli.AUTODISCOVER_PATHS[:] = old_paths + + request.addfinalizer(finalizer) + + return patcher + + +@fixture +def tmp_project_dir(monkeypatch: MonkeyPatch, tmp_path: Path) -> Path: + path = tmp_path / "project_dir" + path.mkdir(exist_ok=True) + monkeypatch.chdir(path) + return path + + +class CreateAppFileFixture(Protocol): + def __call__( + self, + file: Union[str, Path], + directory: Optional[Union[str, Path]] = None, + content: Optional[str] = None, + ) -> Path: + ... + + +@fixture def create_app_file( - file: Union[str, Path], directory: Optional[Union[str, Path]] = None, content: Optional[str] = None -) -> Generator[Path, None, None]: - base = Path.cwd() - if directory: - base = base / directory - base.mkdir() - - tmp_app_file = base / file - tmp_app_file.write_text( - content - or """ -from starlite import Starlite -app = Starlite([]) -""" - ) + tmp_project_dir: Path, + request: FixtureRequest, +) -> CreateAppFileFixture: + def _create_app_file( + file: Union[str, Path], + directory: Optional[Union[str, Path]] = None, + content: Optional[str] = None, + ) -> Path: + base = tmp_project_dir + if directory: + base = base / directory + base.mkdir() + + tmp_app_file = base / file + tmp_app_file.write_text(content or APP_FILE_CONTENT) - try: - yield tmp_app_file - finally: if directory: - shutil.rmtree(directory) + request.addfinalizer(lambda: shutil.rmtree(directory)) # type: ignore[arg-type] else: - tmp_app_file.unlink() + request.addfinalizer(tmp_app_file.unlink) + return tmp_app_file + + return _create_app_file + + +@fixture +def app_file(create_app_file: CreateAppFileFixture) -> Path: + return create_app_file("asgi.py") @fixture @@ -109,12 +130,6 @@ def mock_uvicorn_run(mocker: MockerFixture) -> MagicMock: return mocker.patch("uvicorn.run") -@fixture -def app_file() -> Generator[Path, None, None]: - with create_app_file("asgi.py") as path: - yield path - - @fixture def mock_confirm_ask(mocker: MockerFixture) -> Generator[MagicMock, None, None]: yield mocker.patch("starlite.cli.Confirm.ask", return_value=True) @@ -192,21 +207,23 @@ def test_starlite_env_from_env_host(monkeypatch: MonkeyPatch, app_file: Path) -> ], ) @pytest.mark.parametrize("path", AUTODISCOVER_PATHS) -def test_env_from_env_autodiscover_from_files(path: str, file_content: str) -> None: +def test_env_from_env_autodiscover_from_files( + path: str, file_content: str, create_app_file: CreateAppFileFixture +) -> None: directory = None if "/" in path: directory, path = path.split("/", 1) - with create_app_file(path, directory, content=file_content) as tmp_file_path: - env = StarliteEnv.from_env(None) + tmp_file_path = create_app_file(path, directory, content=file_content) + env = StarliteEnv.from_env(None) assert isinstance(env.app, Starlite) assert env.app_path == f"{_path_to_dotted_path(tmp_file_path.relative_to(Path.cwd()))}:app" -def test_autodiscover_not_found() -> None: +def test_autodiscover_not_found(tmp_project_dir: Path) -> None: with pytest.raises(StarliteCLIException): - _autodiscover_app(None) + _autodiscover_app(None, tmp_project_dir) def test_info_command(mocker: MockerFixture, runner: CliRunner, app_file: Path) -> None: @@ -231,6 +248,7 @@ def test_run_command( port: Optional[int], host: Optional[str], custom_app_file: Optional[Path], + create_app_file: CreateAppFileFixture, set_in_env: bool, ) -> None: mock_show_app_info = mocker.patch("starlite.cli._show_app_info") @@ -264,9 +282,9 @@ def test_run_command( else: host = "127.0.0.1" - with create_app_file(custom_app_file or "asgi.py") as path: + path = create_app_file(custom_app_file or "asgi.py") - result = runner.invoke(cli_command, args) + result = runner.invoke(cli_command, args) assert result.exception is None assert result.exit_code == 0 @@ -297,11 +315,12 @@ def test_run_command_with_autodiscover_app_factory( file_content: str, factory_name: str, patch_autodiscovery_paths: Callable[[List[str]], None], + create_app_file: CreateAppFileFixture, ) -> None: patch_autodiscovery_paths([file_name]) - with create_app_file(file_name, content=file_content) as path: - result = runner.invoke(cli_command, "run") + path = create_app_file(file_name, content=file_content) + result = runner.invoke(cli_command, "run") assert result.exception is None assert result.exit_code == 0 @@ -318,11 +337,12 @@ def test_run_command_with_autodiscover_app_factory( def test_run_command_with_app_factory( runner: CliRunner, mock_uvicorn_run: MagicMock, + create_app_file: CreateAppFileFixture, ) -> None: - with create_app_file("_create_app_with_path.py", content=CREATE_APP_FILE_CONTENT) as path: - app_path = f"{path.stem}:create_app" - result = runner.invoke(cli_command, ["--app", app_path, "run"]) + path = create_app_file("_create_app_with_path.py", content=CREATE_APP_FILE_CONTENT) + app_path = f"{path.stem}:create_app" + result = runner.invoke(cli_command, ["--app", app_path, "run"]) assert result.exception is None assert result.exit_code == 0
Bug: Starlite CLI cannot import project **Describe the bug** I have a very minimal hello world application in Starlite, using Poetry. I have installed python-dotenv, and created a base env file that points to the poetry package. However, whenever I run `starlite info` I get an import error in the cli. I've attempted to debug this through the use of print statements, augmenting python's `sys.path`, as well as importing other installed packages, like `pydantic`. I am able to import my files using `importlib.import_module` from the python REPL, but am unable to in the cli. ```python from starlite import Starlite, get @get("/") def hello() -> str: return "world" app = Starlite(route_handlers=[hello]) ``` **To Reproduce** 1. Generate a Poetry project 2. Install `starlite[full]` 3. Install `python-dotenv` 4. Install `uvicorn` 5. Create a `.env` file pointing to the poetry package 6. Create a basic hello world file in the `__init__.py` (see attachment) 7. Run `starlite info` **Additional context** I am on Starlite Version 1.48.1 Here is the full error message. For context the Poetry package is named `starlite_playground` ``` Using Starlite app from env: 'starlite_playground:app' Traceback (most recent call last): File "/home/ikollipara/Documents/GitHub/starlite-playground/.venv/bin/starlite", line 8, in <module> sys.exit(cli()) ^^^^^ File "/home/ikollipara/Documents/GitHub/starlite-playground/.venv/lib/python3.11/site-packages/click/core.py", line 1130, in __call__ return self.main(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ikollipara/Documents/GitHub/starlite-playground/.venv/lib/python3.11/site-packages/click/core.py", line 1055, in main rv = self.invoke(ctx) ^^^^^^^^^^^^^^^^ File "/home/ikollipara/Documents/GitHub/starlite-playground/.venv/lib/python3.11/site-packages/click/core.py", line 1654, in invoke super().invoke(ctx) File "/home/ikollipara/Documents/GitHub/starlite-playground/.venv/lib/python3.11/site-packages/click/core.py", line 1404, in invoke return ctx.invoke(self.callback, **ctx.params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ikollipara/Documents/GitHub/starlite-playground/.venv/lib/python3.11/site-packages/click/core.py", line 760, in invoke return __callback(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ikollipara/Documents/GitHub/starlite-playground/.venv/lib/python3.11/site-packages/click/decorators.py", line 26, in new_func return f(get_current_context(), *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ikollipara/Documents/GitHub/starlite-playground/.venv/lib/python3.11/site-packages/starlite/cli.py", line 347, in cli ctx.obj = StarliteEnv.from_env(app_path) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ikollipara/Documents/GitHub/starlite-playground/.venv/lib/python3.11/site-packages/starlite/cli.py", line 102, in from_env loaded_app = _autodiscover_app(getenv("STARLITE_APP")) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ikollipara/Documents/GitHub/starlite-playground/.venv/lib/python3.11/site-packages/starlite/cli.py", line 210, in _autodiscover_app return _load_app_from_path(app_path) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ikollipara/Documents/GitHub/starlite-playground/.venv/lib/python3.11/site-packages/starlite/cli.py", line 192, in _load_app_from_path module = importlib.import_module(module_path) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib64/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1142, in _find_and_load_unlocked ModuleNotFoundError: No module named 'starlite_playground' ```
I can't reproduce this on my end. Can you share your `pyproject.toml` and directory layout? Although I have a hunch what's going on. > Create a .env file pointing to the poetry package Does running a separate `poetry install` solve your problem? If you set `STARLITE_APP` to the name of the package as defined in poetry, it could require that this package is actually installed in the current environment, depending on the directory structure / naming.
2023-01-05T18:27:44
litestar-org/litestar
1,114
litestar-org__litestar-1114
[ "1113", "1113" ]
c7ed593ec491401b55881dca9af231b8f99f843a
diff --git a/tools/publish_docs.py b/tools/publish_docs.py --- a/tools/publish_docs.py +++ b/tools/publish_docs.py @@ -12,7 +12,7 @@ parser.add_argument("--latest", action="store_true") -def update_versions_file(version: str) -> None: +def add_to_versions_file(version: str, latest: bool) -> None: versions_file = Path("versions.json") versions = [] if versions_file.exists(): @@ -24,6 +24,11 @@ def update_versions_file(version: str) -> None: else: versions.insert(0, new_version_spec) + if latest: + for version in versions: + version["aliases"] = [] + versions[0]["aliases"] = ["latest"] + versions_file.write_text(json.dumps(versions)) @@ -32,7 +37,7 @@ def make_version(version: str, push: bool, latest: bool) -> None: subprocess.run(["git", "checkout", "gh-pages"], check=True) - update_versions_file(version) + add_to_versions_file(version, latest) docs_src_path = Path("docs/_build/html") docs_dest_path = Path(version)
Documentation: "older version" warning present on latest Every page under https://starlite-api.github.io/starlite/latest/ has the "You are viewing the documentation for an older version of Starlite. Click here to get to the latest version" warning, which links back to the welcome page. The message is not present in https://starlite-api.github.io/starlite/1.50/, https://starlite-api.github.io/starlite/1.49/, or https://starlite-api.github.io/starlite/1.47/. Documentation: "older version" warning present on latest Every page under https://starlite-api.github.io/starlite/latest/ has the "You are viewing the documentation for an older version of Starlite. Click here to get to the latest version" warning, which links back to the welcome page. The message is not present in https://starlite-api.github.io/starlite/1.50/, https://starlite-api.github.io/starlite/1.49/, or https://starlite-api.github.io/starlite/1.47/.
Yep, seeing this too. Thanks for the report! `versions.json` still shows 1.49 with the "latest" alias: https://github.com/starlite-api/starlite/blob/cf7772c782fab24d090f9b4b5d9a201d163b6a62/versions.json#L1 However, this doesn't explain why the the banner doesn't show on 1.48, for example. > However, this doesn't explain why the the banner doesn't show on 1.48, for example. Seems to be a big in the workaround I added to make the versioning compatible with the one we had for mkdocs. I’m gonna put a PR to fix this later. `getSelectedVersion()` returns "latest": ![image](https://user-images.githubusercontent.com/20659309/215424544-c41d6638-a941-40f4-a2ac-bbb81cefbf5b.png) the latest version is defined here, and is "1.50" in this case, and the way this is selected means it will always be the 0th entry in that array of version, irrespective if it is actually aliased as "latest" or not. https://github.com/starlite-api/starlite/blob/c7ed593ec491401b55881dca9af231b8f99f843a/docs/_static/js/version_select.js#L91 So, `selectedVersion` will never match `latestVersion` here when `selectedVersion` is "latest": https://github.com/starlite-api/starlite/blob/c7ed593ec491401b55881dca9af231b8f99f843a/docs/_static/js/version_select.js#L34 Perhaps, `getSelectedVersion()` should resolve the actual version of the "latest" alias? OK, will leave it with you @provinzkraut > However, this doesn't explain why the the banner doesn't show on 1.48, for example. Quick correction - I do get a banner for 1.48, but not 1.47 or 1.49 > Perhaps, getSelectedVersion() should resolve the actual version of the "latest" alias? This would be a bit tricky since we currently don't actually use the aliasing anymore. I didn't want to add the complexity of re-aliasing and such to the docs publishing logic, and we don't actually need it, since we have a pre-defined versioning scheme, so no need for the flexibility really. The solution here would be to just hardcode `"latest"` in the check for the latest version, so that it always returns true for `"latest"`. So this is why 1.49 is "latest" in versions.json? It doesn't actually mean anything in practice? This is the versioning logic that `mike` used. I simply haven't touched that. The idea was to just keep it as-is, so everything would continue working on the older versions of the documentation. Seems like I'm going to have to remove that alias from the versioning file and slap it on to the actually *latest* version so our old docs display the correct warnings + offer redirects. For our docs, it doesn't do anything, that's correct. However, since it looks like we're going to have to use the alias to make the older docs work, we might as well use it for ours as well. Yep, seeing this too. Thanks for the report! `versions.json` still shows 1.49 with the "latest" alias: https://github.com/starlite-api/starlite/blob/cf7772c782fab24d090f9b4b5d9a201d163b6a62/versions.json#L1 However, this doesn't explain why the the banner doesn't show on 1.48, for example. > However, this doesn't explain why the the banner doesn't show on 1.48, for example. Seems to be a big in the workaround I added to make the versioning compatible with the one we had for mkdocs. I’m gonna put a PR to fix this later. `getSelectedVersion()` returns "latest": ![image](https://user-images.githubusercontent.com/20659309/215424544-c41d6638-a941-40f4-a2ac-bbb81cefbf5b.png) the latest version is defined here, and is "1.50" in this case, and the way this is selected means it will always be the 0th entry in that array of version, irrespective if it is actually aliased as "latest" or not. https://github.com/starlite-api/starlite/blob/c7ed593ec491401b55881dca9af231b8f99f843a/docs/_static/js/version_select.js#L91 So, `selectedVersion` will never match `latestVersion` here when `selectedVersion` is "latest": https://github.com/starlite-api/starlite/blob/c7ed593ec491401b55881dca9af231b8f99f843a/docs/_static/js/version_select.js#L34 Perhaps, `getSelectedVersion()` should resolve the actual version of the "latest" alias? OK, will leave it with you @provinzkraut > However, this doesn't explain why the the banner doesn't show on 1.48, for example. Quick correction - I do get a banner for 1.48, but not 1.47 or 1.49 > Perhaps, getSelectedVersion() should resolve the actual version of the "latest" alias? This would be a bit tricky since we currently don't actually use the aliasing anymore. I didn't want to add the complexity of re-aliasing and such to the docs publishing logic, and we don't actually need it, since we have a pre-defined versioning scheme, so no need for the flexibility really. The solution here would be to just hardcode `"latest"` in the check for the latest version, so that it always returns true for `"latest"`. So this is why 1.49 is "latest" in versions.json? It doesn't actually mean anything in practice? This is the versioning logic that `mike` used. I simply haven't touched that. The idea was to just keep it as-is, so everything would continue working on the older versions of the documentation. Seems like I'm going to have to remove that alias from the versioning file and slap it on to the actually *latest* version so our old docs display the correct warnings + offer redirects. For our docs, it doesn't do anything, that's correct. However, since it looks like we're going to have to use the alias to make the older docs work, we might as well use it for ours as well.
2023-01-30T10:50:53
litestar-org/litestar
1,190
litestar-org__litestar-1190
[ "1120" ]
4cc867c0c5f49449b64932a391029b41b295b14c
diff --git a/starlite/app.py b/starlite/app.py --- a/starlite/app.py +++ b/starlite/app.py @@ -15,7 +15,7 @@ ) from pydantic_openapi_schema import construct_open_api_with_schema_class -from typing_extensions import TypedDict +from typing_extensions import Self, TypedDict from starlite.asgi import ASGIRouter from starlite.asgi.utils import get_route_handlers, wrap_in_exception_handler @@ -446,6 +446,18 @@ async def __call__( scope["state"] = {} await self.asgi_handler(scope, receive, self._wrap_send(send=send, scope=scope)) # type: ignore[arg-type] + @classmethod + def from_config(cls, config: AppConfig) -> Self: + """Initialize a ``Starlite`` application from a configuration instance. + + Args: + config: An instance of :class:`AppConfig` <startlite.config.AppConfig> + + Returns: + An instance of ``Starlite`` application. + """ + return cls(**dict(config)) + def register( # type: ignore[override] self, value: "ControllerRouterHandler", add_to_openapi_schema: bool = False ) -> None: diff --git a/starlite/config/app.py b/starlite/config/app.py --- a/starlite/config/app.py +++ b/starlite/config/app.py @@ -6,6 +6,7 @@ from starlite.connection import Request, WebSocket from starlite.datastructures import CacheControlHeader, ETag from starlite.di import Provide +from starlite.events.emitter import SimpleEventEmitter from starlite.events.listener import EventListener from starlite.plugins import PluginProtocol from starlite.types import ( @@ -50,7 +51,7 @@ class AppConfig(BaseModel): class Config(BaseConfig): arbitrary_types_allowed = True - after_exception: List[AfterExceptionHookHandler] + after_exception: List[AfterExceptionHookHandler] = [] """An application level :class:`exception hook handler <starlite.types.AfterExceptionHookHandler>` or list thereof. This hook is called after an exception occurs. In difference to exception handlers, it is not meant to return a @@ -67,12 +68,12 @@ class Config(BaseConfig): :class:`Request <starlite.connection.Request>` object and should not return any values. """ - after_shutdown: List[LifeSpanHookHandler] + after_shutdown: List[LifeSpanHookHandler] = [] """An application level :class:`life-span hook handler <starlite.types.LifeSpanHookHandler>` or list thereof. This hook is called during the ASGI shutdown, after all callables in the 'on_shutdown' list have been called. """ - after_startup: List[LifeSpanHookHandler] + after_startup: List[LifeSpanHookHandler] = [] """An application level :class:`life-span hook handler <starlite.types.LifeSpanHookHandler>` or list thereof. This hook is called during the ASGI startup, after all callables in the 'on_startup' list have been called. @@ -85,22 +86,22 @@ class Config(BaseConfig): :class:`Request <starlite.connection.Request>` instance and any non-``None`` return value is used for the response, bypassing the route handler. """ - before_send: List[BeforeMessageSendHookHandler] + before_send: List[BeforeMessageSendHookHandler] = [] """An application level :class:`before send hook handler <starlite.types.BeforeMessageSendHookHandler>` or list thereof. This hook is called when the ASGI send function is called. """ - before_shutdown: List[LifeSpanHookHandler] + before_shutdown: List[LifeSpanHookHandler] = [] """An application level :class:`life-span hook handler <starlite.types.LifeSpanHookHandler>` or list thereof. This hook is called during the ASGI shutdown, before any callables in the 'on_shutdown' list have been called. """ - before_startup: List[LifeSpanHookHandler] + before_startup: List[LifeSpanHookHandler] = [] """An application level :class:`life-span hook handler <starlite.types.LifeSpanHookHandler>` or list thereof. This hook is called during the ASGI startup, before any callables in the 'on_startup' list have been called. """ - cache_config: CacheConfig + cache_config: CacheConfig = CacheConfig() """Configures caching behavior of the application.""" cache_control: Optional[CacheControlHeader] """A ``cache-control`` header of type :class:`CacheControlHeader <starlite.datastructures.CacheControlHeader>` to add to route @@ -116,67 +117,67 @@ class Config(BaseConfig): """If set this enables the builtin CORS middleware.""" csrf_config: Optional[CSRFConfig] """If set this enables the builtin CSRF middleware.""" - debug: bool + debug: bool = False """If ``True``, app errors rendered as HTML with a stack trace.""" - dependencies: Dict[str, Provide] + dependencies: Dict[str, Provide] = {} """A string keyed dictionary of dependency :class:`Provider <starlite.datastructures.Provide>` instances.""" etag: Optional[ETag] """An ``etag`` header of type :class:`ETag <starlite.datastructures.ETag>` to add to route handlers of this app. Can be overridden by route handlers. """ - event_emitter_backend: Type[BaseEventEmitterBackend] + event_emitter_backend: Type[BaseEventEmitterBackend] = SimpleEventEmitter """A subclass of :class:`BaseEventEmitterBackend <starlite.events.emitter.BaseEventEmitterBackend>`.""" - exception_handlers: ExceptionHandlersMap + exception_handlers: ExceptionHandlersMap = {} """A dictionary that maps handler functions to status codes and/or exception types.""" - guards: List[Guard] + guards: List[Guard] = [] """A list of :class:`Guard <starlite.types.Guard>` callables.""" - initial_state: InitialStateType + initial_state: InitialStateType = {} """An object from which to initialize the app state.""" - listeners: List[EventListener] + listeners: List[EventListener] = [] """A list of :class:`EventListener <starlite.events.listener.EventListener>`.""" logging_config: Optional[BaseLoggingConfig] """An instance of :class:`BaseLoggingConfig <starlite.config.logging.BaseLoggingConfig>` subclass.""" middleware: List[Middleware] """A list of :class:`Middleware <starlite.types.Middleware>`.""" - on_shutdown: List[LifeSpanHandler] + on_shutdown: List[LifeSpanHandler] = [] """A list of :class:`LifeSpanHandler <starlite.types.LifeSpanHandler>` called during application shutdown.""" - on_startup: List[LifeSpanHandler] + on_startup: List[LifeSpanHandler] = [] """A list of :class:`LifeSpanHandler <starlite.types.LifeSpanHandler>` called during application startup.""" openapi_config: Optional[OpenAPIConfig] """Defaults to :data:`DEFAULT_OPENAPI_CONFIG <starlite.app.DEFAULT_OPENAPI_CONFIG>`""" - opt: Dict[str, Any] + opt: Dict[str, Any] = {} """A string keyed dictionary of arbitrary values that can be accessed in :class:`Guards <starlite.types.Guard>` or wherever you have access to :class:`Request <starlite.connection.request.Request>` or :class:`ASGI Scope <starlite.types.Scope>`. Can be overridden by routers and router handlers. """ - parameters: ParametersMap + parameters: ParametersMap = {} """A mapping of :class:`Parameter <starlite.params.Parameter>` definitions available to all application paths.""" - plugins: List[PluginProtocol] + plugins: List[PluginProtocol] = [] """List of :class:`SerializationPluginProtocol <starlite.plugins.base.SerializationPluginProtocol>`.""" request_class: Optional[Type[Request]] """An optional subclass of :class:`Request <starlite.connection.request.Request>` to use for http connections.""" response_class: Optional[ResponseType] """A custom subclass of [starlite.response.Response] to be used as the app's default response.""" - response_cookies: ResponseCookies + response_cookies: ResponseCookies = [] """A list of [Cookie](starlite.datastructures.Cookie] instances.""" - response_headers: ResponseHeadersMap + response_headers: ResponseHeadersMap = {} """A string keyed dictionary mapping :class:`ResponseHeader <starlite.datastructures.ResponseHeader>` instances.""" - route_handlers: List[ControllerRouterHandler] + route_handlers: List[ControllerRouterHandler] = [] """A required list of route handlers, which can include instances of :class:`Router <starlite.router.Router>`, subclasses of. :class:`Controller <starlite.controller.Controller>` or any function decorated by the route handler decorators. """ - security: List[SecurityRequirement] + security: List[SecurityRequirement] = [] """A list of dictionaries that will be added to the schema of all route handlers in the application. See. :class:`SecurityRequirement <pydantic_openapi_schema.v3_1_0.security_requirement.SecurityRequirement>` for details. """ - static_files_config: List[StaticFilesConfig] + static_files_config: List[StaticFilesConfig] = [] """An instance or list of :class:`StaticFilesConfig <starlite.config.StaticFilesConfig>`.""" - tags: List[str] + tags: List[str] = [] """A list of string tags that will be appended to the schema of all route handlers under the application.""" template_config: Optional[TemplateConfig] """An instance of :class:`TemplateConfig <starlite.config.TemplateConfig>`."""
Enhancement: Allow configuration of an application via an `AppConfig` instance We already have `AppConfig` in place, so it would be nice to be able to do something like ```python from starlite import Starlite, AppConfig config = AppConfig(...) app = Starlite.from_config(config) ```
Cool, why not How would you recommend this be implemented ? Should the from_config just call __init__ under the hood ``` @classmethod def from_config(cls, config): return cls(**config) // this wont work since config is not a dict ``` Something like this ? > Should the from_config just call init under the hood Something like calling `Starlite(**config.dict(exclude_unset=True))` would certainly work, but then we just turn around and construct another `AppConfig` object inside `__init__` (not that performance is an issue, as it only happens once). We could add `app_config: Optional[AppConfig] = None` to the `Starlite.__init__()` signature, and if it is provided, we use that as the initial config object that is passed to the `on_app_init` hooks, in lieu of constructing our own. If that was the case, the constructor method wouldn't be necessary as we could simply call `Starlite(config=AppConfig(...))`, but we'd have to work out precedence rules, e.g., if both `route_handlers` and `config` were given to the constructor, then should they be merged, would one take precedence over the other etc etc. Starlite has _a lot_ of `__init__` params, maybe an evolution into 2.0 could be adding the `config` object to the signature, and then in 2.0 making config of the app _only_ via config object. > maybe an evolution into 2.0 could be adding the config object to the signature, and then in 2.0 making config of the app only via config object. I'm not sure about that. Feels a bit cumbersome *having* to construct a config object and pass it immediately to `Starlite`. I think for now, the best approach would be to do what you described, but `@overload` `__init__`, to only allow either kwargs or a config object, and then just discard all kwargs if a config object is passed. > I think for now, the best approach would be to do what you described, but @overload __init__, to only allow either kwargs or a config object, and then just discard all kwargs if a config object is passed. SGTM. We'd need to make `route_handlers` optional for that, but I can't see why that should be a problem, and also put default values on the `AppConfig` object Can we initialize AppConfig from .env's ? No. It's mostly Python objects, so adding `.env`-file support doesn't make a lot of sense. There's not a lot of settings there that would lend to being directly set by environment. I go pretty heavy on the config-via-environment approach in [starlite-saqlalchemy](https://github.com/topsport-com-au/starlite-saqlalchemy/blob/main/src/starlite_saqlalchemy/settings.py), but mostly that is using environment to configure things like cache config, openapi config, sqlalchemy plugin etc, which are then passed to the app via `AppConfig` as a `on_app_init` hook. @provinzkraut @peterschutt Thank you for informing, One more question generally we could set defaults in dunder init for AppConfig or create a settings.py like how django does it (Although I think that would over complicate things for this issue) > One more question generally we could set defaults in dunder init for AppConfig If you take a look at `AppConfig`, you'll see that it's a Pydantic model. So the correct way to set defaults would be on the class attributes themselves. I don't think `settings.py` fits the Starlite way of doing things, and I don't see any benefit of this. Even for Django this makes things more complicated. It's opaque "automagic", which almost never is a good idea. ok thanks for the help > I'm not sure about that. Feels a bit cumbersome _having_ to construct a config object and pass it immediately to `Starlite`. Yeh OK, so on retrospect replacing all config would be a bit extreme, but could we still benefit from consolidating some of the configs into a config object, just like we do for `openapi_config`, `static_files_config` etc etc. The one that stands out to me most is the lifecycle hooks., having a `LifecycleHookConfig` makes sense as a grouping IMO, and would significantly reduce the number of parameters to the application. > The one that stands out to me most is the lifecycle hooks., having a `LifecycleHookConfig` makes sense as a grouping IMO, and would significantly reduce the number of parameters to the application. Well it would certainly make sense, and it'd be 8 parameters we could remove. On the other hand ```python app = Starlite(..., on_startup=on_startup) ``` is way more convenient than ```python app = Starlite(..., lifecycle_hooks_config=LifecycleHooksConfig(on_startup=on_startup)) ``` @wassafshahzad were you working on this? @JacobCoffee - you can work on this > @wassafshahzad were you working on this? > Yes will have a pr up by tomorrow
2023-02-12T20:34:29
litestar-org/litestar
1,225
litestar-org__litestar-1225
[ "1210" ]
4201f060e6a5576d94e20025522cbeda2ac61cbf
diff --git a/starlite/openapi/schema.py b/starlite/openapi/schema.py --- a/starlite/openapi/schema.py +++ b/starlite/openapi/schema.py @@ -1,3 +1,4 @@ +from dataclasses import replace from datetime import datetime from decimal import Decimal from enum import Enum, EnumMeta @@ -46,6 +47,7 @@ CursorPagination, OffsetPagination, ) +from starlite.utils.types import make_non_optional_union if TYPE_CHECKING: from starlite.plugins.base import OpenAPISchemaPluginProtocol @@ -333,15 +335,13 @@ def create_schema( field: "SignatureField", generate_examples: bool, plugins: List["OpenAPISchemaPluginProtocol"], - ignore_optional: bool = False, ) -> "Schema": """Create a Schema model for a given SignatureField and if needed - recursively traverse its children as well.""" - - if field.is_optional and not ignore_optional: + if field.is_optional: + non_optional_field = replace(field, field_type=make_non_optional_union(field.field_type)) non_optional_schema = create_schema( - field=field, + field=non_optional_field, generate_examples=False, - ignore_optional=True, plugins=plugins, ) schema = Schema( @@ -387,8 +387,7 @@ def create_schema( else: # value is not a complex typing - hence we can try and get the value schema directly schema = get_schema_for_field_type(field=field, plugins=plugins) - if not ignore_optional: - schema = update_schema_with_signature_field(schema=schema, signature_field=field) + schema = update_schema_with_signature_field(schema=schema, signature_field=field) if not schema.examples and generate_examples: schema.examples = create_examples_for_field(field=field) return schema
Bug: Optional types generate incorrect OpenAPI schemas **Describe the bug** 1. Optional types in query parameters don't seem to play well with OpenAPI, resulting in a bad schema, *except* that upon some more testing if there is more than one non-None type in the annotation it works. A query parameter annotated `int | None` produces incorrectly: ``` { "oneOf": [ { "type": null" }, { "oneOf": [] } ]} ``` While one annotated `int | str | date | None` produces correctly: ``` { "oneOf": [ { "type": "null" }, { "type": "integer" }, { "type": "string" }, { "type": "string", "format": "date" } ]} ``` 2. Additionally, optional types are being assumed to be optional parameters, resulting in `"required": false` regardless of whether the parameter has a default value or not. 3. And finally, route return types that are optional are _mostly_ correct, but for some reason include an empty node (e.g. `{ "oneOf": [ { "type": "null" }, { "type": "integer" }, {} }`). This results in `/schema/redoc` including a possible type of `Any`. **To Reproduce** (I ran this on 3.11, but IIRC 3.8+ for `| None` should work. I also tried with `Optional` and got the same results.) As a minimal example: ```py # starlite_optionals.py from datetime import date from starlite import Starlite, get @get("/a") def a(v: int | None) -> int | None: return v @get("/b") def b(v: int | str | date | None) -> int | str | date | None: return v @get("/c") def c(v: int | None = None) -> int | None: return v @get("/d") def d(v: int | str | date | None = None) -> int | str | date | None: return v app = Starlite(route_handlers=[a, b, c, d], debug=True) ``` Check the generated schema below, or by running `uvicorn starlite_optionals:app` and navigating to <http://127.0.0.1:8000/schema/openapi.json> and/or <http://127.0.0.1:8000/schema/>. <details> <summary>Generated OpenAPI schema.</summary> ```json { "openapi": "3.1.0", "info": { "title": "Starlite API", "version": "1.0.0" }, "servers": [ { "url": "/" } ], "paths": { "/a": { "get": { "operationId": "AA", "parameters": [ { "name": "v", "in": "query", "required": false, "deprecated": false, "allowEmptyValue": false, "allowReserved": false, "schema": { "oneOf": [ { "type": "null" }, { "oneOf": [] } ] } } ], "responses": { "200": { "description": "Request fulfilled, document follows", "headers": {}, "content": { "application/json": { "schema": { "oneOf": [ { "type": "null" }, { "type": "integer" }, {} ] } } } }, "400": { "description": "Bad request syntax or unsupported method", "content": { "application/json": { "schema": { "properties": { "status_code": { "type": "integer" }, "detail": { "type": "string" }, "extra": { "additionalProperties": {}, "type": [ "null", "object", "array" ] } }, "type": "object", "required": [ "detail", "status_code" ], "description": "Validation Exception", "examples": [ { "status_code": 400, "detail": "Bad Request", "extra": {} } ] } } } } }, "deprecated": false } }, "/b": { "get": { "operationId": "BB", "parameters": [ { "name": "v", "in": "query", "required": false, "deprecated": false, "allowEmptyValue": false, "allowReserved": false, "schema": { "oneOf": [ { "type": "null" }, { "type": "integer" }, { "type": "string" }, { "type": "string", "format": "date" } ] } } ], "responses": { "200": { "description": "Request fulfilled, document follows", "headers": {}, "content": { "application/json": { "schema": { "oneOf": [ { "type": "null" }, { "type": "integer" }, { "type": "string" }, { "type": "string", "format": "date" }, {} ] } } } }, "400": { "description": "Bad request syntax or unsupported method", "content": { "application/json": { "schema": { "properties": { "status_code": { "type": "integer" }, "detail": { "type": "string" }, "extra": { "additionalProperties": {}, "type": [ "null", "object", "array" ] } }, "type": "object", "required": [ "detail", "status_code" ], "description": "Validation Exception", "examples": [ { "status_code": 400, "detail": "Bad Request", "extra": {} } ] } } } } }, "deprecated": false } }, "/c": { "get": { "operationId": "CC", "parameters": [ { "name": "v", "in": "query", "required": false, "deprecated": false, "allowEmptyValue": false, "allowReserved": false, "schema": { "oneOf": [ { "type": "null" }, { "oneOf": [] } ] } } ], "responses": { "200": { "description": "Request fulfilled, document follows", "headers": {}, "content": { "application/json": { "schema": { "oneOf": [ { "type": "null" }, { "type": "integer" }, {} ] } } } }, "400": { "description": "Bad request syntax or unsupported method", "content": { "application/json": { "schema": { "properties": { "status_code": { "type": "integer" }, "detail": { "type": "string" }, "extra": { "additionalProperties": {}, "type": [ "null", "object", "array" ] } }, "type": "object", "required": [ "detail", "status_code" ], "description": "Validation Exception", "examples": [ { "status_code": 400, "detail": "Bad Request", "extra": {} } ] } } } } }, "deprecated": false } }, "/d": { "get": { "operationId": "DD", "parameters": [ { "name": "v", "in": "query", "required": false, "deprecated": false, "allowEmptyValue": false, "allowReserved": false, "schema": { "oneOf": [ { "type": "null" }, { "type": "integer" }, { "type": "string" }, { "type": "string", "format": "date" } ] } } ], "responses": { "200": { "description": "Request fulfilled, document follows", "headers": {}, "content": { "application/json": { "schema": { "oneOf": [ { "type": "null" }, { "type": "integer" }, { "type": "string" }, { "type": "string", "format": "date" }, {} ] } } } }, "400": { "description": "Bad request syntax or unsupported method", "content": { "application/json": { "schema": { "properties": { "status_code": { "type": "integer" }, "detail": { "type": "string" }, "extra": { "additionalProperties": {}, "type": [ "null", "object", "array" ] } }, "type": "object", "required": [ "detail", "status_code" ], "description": "Validation Exception", "examples": [ { "status_code": 400, "detail": "Bad Request", "extra": {} } ] } } } } }, "deprecated": false } } } } ``` </details>
2023-02-21T04:16:24
litestar-org/litestar
1,229
litestar-org__litestar-1229
[ "1228" ]
e21052705875d0657cbe3aeeeadc1a074e7b354e
diff --git a/starlite/utils/extractors.py b/starlite/utils/extractors.py --- a/starlite/utils/extractors.py +++ b/starlite/utils/extractors.py @@ -35,10 +35,7 @@ def obfuscate(values: Dict[str, Any], fields_to_obfuscate: Set[str]) -> Dict[str Returns: A dictionary with obfuscated strings """ - for key in values: - if key.lower() in fields_to_obfuscate: - values[key] = "*****" - return values + return {key: "*****" if key.lower() in fields_to_obfuscate else value for key, value in values.items()} RequestExtractorField = Literal[
diff --git a/tests/middleware/test_logging_middleware.py b/tests/middleware/test_logging_middleware.py --- a/tests/middleware/test_logging_middleware.py +++ b/tests/middleware/test_logging_middleware.py @@ -6,8 +6,10 @@ from starlite import Cookie, LoggingConfig, Response, StructLoggingConfig, get, post from starlite.config.compression import CompressionConfig +from starlite.connection import Request from starlite.middleware import LoggingMiddlewareConfig -from starlite.status_codes import HTTP_200_OK +from starlite.middleware.session.memory_backend import MemoryBackendConfig +from starlite.status_codes import HTTP_200_OK, HTTP_201_CREATED from starlite.testing import create_test_client if TYPE_CHECKING: @@ -190,3 +192,34 @@ async def hello_world_handler() -> Dict[str, str]: response = client.get("/") assert response.status_code == HTTP_200_OK assert len(caplog.messages) == 2 + + +def test_logging_middleware_with_session_middleware() -> None: + # https://github.com/starlite-api/starlite/issues/1228 + + @post("/") + async def set_session(request: Request) -> None: + request.set_session({"hello": "world"}) + + @get("/") + async def get_session() -> None: + pass + + logging_middleware_config = LoggingMiddlewareConfig() + session_config = MemoryBackendConfig() + + with create_test_client( + [set_session, get_session], + logging_config=LoggingConfig(), + middleware=[logging_middleware_config.middleware, session_config.middleware], + ) as client: + response = client.post("/") + assert response.status_code == HTTP_201_CREATED + assert "session" in client.cookies + assert client.cookies["session"] != "*****" + session_id = client.cookies["session"] + + response = client.get("/") + assert response.status_code == HTTP_200_OK + assert "session" in client.cookies + assert client.cookies["session"] == session_id
Bug: LoggingMiddleware is sending obfuscated session id to client **Describe the bug** When using the logging middleware and session middleware together, the logging middleware's cookie obfuscation is overwriting the session name with "*****" and that name is being pushed down to the client. The initial set-cookie has the correct session id but subsequent requests do not. **To Reproduce** I created a test function in tests/middleware/test_logging_middleware.py which I believe confirms the bug: ```python def test_logging_with_session_middleware() -> None: @post("/") async def set_session(request: Request) -> None: request.set_session({"hello": "world"}) @get("/") async def get_session() -> None: pass logging_middleware_config = LoggingMiddlewareConfig() session_config = MemoryBackendConfig() with create_test_client( [set_session, get_session], logging_config=LoggingConfig(), middleware=[logging_middleware_config.middleware, session_config.middleware], ) as client: response = client.post("/") assert response.status_code == HTTP_201_CREATED assert len(client.cookies.get("session", "")) == 64 response = client.get("/") assert response.status_code == HTTP_200_OK assert len(client.cookies.get("session", "")) == 64 ``` The test results in the following exception: ``` > assert len(client.cookies.get("session", "")) == 64 E AssertionError: assert 5 == 64 E + where 5 = len('*****') E + where '*****' = <bound method Cookies.get of <Cookies[<Cookie session=***** for testserver.local />]>>('session', '') E + where <bound method Cookies.get of <Cookies[<Cookie session=***** for testserver.local />]>> = <Cookies[<Cookie session=***** for testserver.local />]>.get E + where <Cookies[<Cookie session=***** for testserver.local />]> = <starlite.testing.client.sync_client.TestClient object at 0x7f4cbf7bea40>.cookies ``` **Additional Context** Starlite version: 1.51.4
2023-02-21T14:53:36
litestar-org/litestar
1,231
litestar-org__litestar-1231
[ "1228" ]
0b7e3a2b0af5b5635becf3d2326453d6f0cef0d8
diff --git a/starlite/utils/extractors.py b/starlite/utils/extractors.py --- a/starlite/utils/extractors.py +++ b/starlite/utils/extractors.py @@ -25,10 +25,7 @@ def obfuscate(values: dict[str, Any], fields_to_obfuscate: set[str]) -> dict[str Returns: A dictionary with obfuscated strings """ - for key in values: - if key.lower() in fields_to_obfuscate: - values[key] = "*****" - return values + return {key: "*****" if key.lower() in fields_to_obfuscate else value for key, value in values.items()} RequestExtractorField = Literal[
diff --git a/tests/middleware/test_logging_middleware.py b/tests/middleware/test_logging_middleware.py --- a/tests/middleware/test_logging_middleware.py +++ b/tests/middleware/test_logging_middleware.py @@ -7,14 +7,16 @@ from starlite import Response, get, post from starlite.config.compression import CompressionConfig from starlite.config.logging import LoggingConfig, StructLoggingConfig +from starlite.connection import Request from starlite.datastructures import Cookie from starlite.middleware.logging import LoggingMiddlewareConfig -from starlite.status_codes import HTTP_200_OK +from starlite.status_codes import HTTP_200_OK, HTTP_201_CREATED from starlite.testing import create_test_client if TYPE_CHECKING: from _pytest.logging import LogCaptureFixture + from starlite.middleware.session.server_side import ServerSideSessionConfig from starlite.types.callable_types import GetLogger @@ -210,3 +212,33 @@ def test_logging_middleware_log_fields(get_logger: "GetLogger", caplog: "LogCapt assert caplog.messages[0] == "HTTP Request: path=/" assert caplog.messages[1] == "HTTP Response: status_code=200" + + +def test_logging_middleware_with_session_middleware(session_backend_config_memory: "ServerSideSessionConfig") -> None: + # https://github.com/starlite-api/starlite/issues/1228 + + @post("/") + async def set_session(request: Request) -> None: + request.set_session({"hello": "world"}) + + @get("/") + async def get_session() -> None: + pass + + logging_middleware_config = LoggingMiddlewareConfig() + + with create_test_client( + [set_session, get_session], + logging_config=LoggingConfig(), + middleware=[logging_middleware_config.middleware, session_backend_config_memory.middleware], + ) as client: + response = client.post("/") + assert response.status_code == HTTP_201_CREATED + assert "session" in client.cookies + assert client.cookies["session"] != "*****" + session_id = client.cookies["session"] + + response = client.get("/") + assert response.status_code == HTTP_200_OK + assert "session" in client.cookies + assert client.cookies["session"] == session_id
Bug: LoggingMiddleware is sending obfuscated session id to client **Describe the bug** When using the logging middleware and session middleware together, the logging middleware's cookie obfuscation is overwriting the session name with "*****" and that name is being pushed down to the client. The initial set-cookie has the correct session id but subsequent requests do not. **To Reproduce** I created a test function in tests/middleware/test_logging_middleware.py which I believe confirms the bug: ```python def test_logging_with_session_middleware() -> None: @post("/") async def set_session(request: Request) -> None: request.set_session({"hello": "world"}) @get("/") async def get_session() -> None: pass logging_middleware_config = LoggingMiddlewareConfig() session_config = MemoryBackendConfig() with create_test_client( [set_session, get_session], logging_config=LoggingConfig(), middleware=[logging_middleware_config.middleware, session_config.middleware], ) as client: response = client.post("/") assert response.status_code == HTTP_201_CREATED assert len(client.cookies.get("session", "")) == 64 response = client.get("/") assert response.status_code == HTTP_200_OK assert len(client.cookies.get("session", "")) == 64 ``` The test results in the following exception: ``` > assert len(client.cookies.get("session", "")) == 64 E AssertionError: assert 5 == 64 E + where 5 = len('*****') E + where '*****' = <bound method Cookies.get of <Cookies[<Cookie session=***** for testserver.local />]>>('session', '') E + where <bound method Cookies.get of <Cookies[<Cookie session=***** for testserver.local />]>> = <Cookies[<Cookie session=***** for testserver.local />]>.get E + where <Cookies[<Cookie session=***** for testserver.local />]> = <starlite.testing.client.sync_client.TestClient object at 0x7f4cbf7bea40>.cookies ``` **Additional Context** Starlite version: 1.51.4
2023-02-21T16:16:50