id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
158,246 | from fastapi import FastAPI, Query
async def read_items(q: list[str] | None = Query(None)):
query_items = {"q": q}
return query_items | null |
158,247 | from typing import Optional
from fastapi import FastAPI, Query
async def read_items(q: Optional[str] = Query(None, min_length=3, max_length=50)):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results | null |
158,248 | from typing import Optional
from fastapi import FastAPI, Query
async def read_items(q: Optional[list[str]] = Query(None)):
query_items = {"q": q}
return query_items | null |
158,249 | from fastapi import FastAPI, Query
async def read_items(
q: str | None = Query(None, min_length=3, max_length=50, regex="^fixedquery$")
):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results | null |
158,250 | from typing import Optional
from fastapi import FastAPI, Query
async def read_items(
hidden_query: Optional[str] = Query(None, include_in_schema=False)
):
if hidden_query:
return {"hidden_query": hidden_query}
else:
return {"hidden_query": "Not found"} | null |
158,251 | from fastapi import FastAPI, Query
async def read_items(
q: str
| None = Query(
None,
alias="item-query",
title="Query string",
description="Query string for the items to search in the database that have a good match",
min_length=3,
max_length=50,
regex="^fixedquery$",
deprecated=True,
)
):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results | null |
158,252 | from fastapi import FastAPI, Query
async def read_items(q: str = Query("fixedquery", min_length=3)):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results | null |
158,253 | from typing import List
from fastapi import FastAPI, Query
async def read_items(q: List[str] = Query(["foo", "bar"])):
query_items = {"q": q}
return query_items | null |
158,254 | from typing import Optional
from fastapi import FastAPI, Query
async def read_items(
q: Optional[str] = Query(None, title="Query string", min_length=3)
):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results | null |
158,255 | from fastapi import FastAPI, Query
async def read_items(q: list = Query([])):
query_items = {"q": q}
return query_items | null |
158,256 | from fastapi import FastAPI, Query
async def read_items(hidden_query: str | None = Query(None, include_in_schema=False)):
if hidden_query:
return {"hidden_query": hidden_query}
else:
return {"hidden_query": "Not found"} | null |
158,257 | from typing import Optional
from fastapi import FastAPI, Query
async def read_items(
q: Optional[str] = Query(
None,
title="Query string",
description="Query string for the items to search in the database that have a good match",
min_length=3,
)
):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results | null |
158,258 | from typing import Optional
from fastapi import FastAPI, Query
async def read_items(q: Optional[str] = Query(None, max_length=50)):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results | null |
158,259 | from fastapi import FastAPI, Query
async def read_items(q: str | None = Query(None, min_length=3, max_length=50)):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results | null |
158,260 | from functools import lru_cache
from fastapi import Depends, FastAPI
from . import config
def get_settings():
return config.Settings()
async def info(settings: config.Settings = Depends(get_settings)):
return {
"app_name": settings.app_name,
"admin_email": settings.admin_email,
"items_per_user": settings.items_per_user,
} | null |
158,261 | from fastapi import FastAPI
from pydantic import BaseSettings
settings = Settings()
async def info():
return {
"app_name": settings.app_name,
"admin_email": settings.admin_email,
"items_per_user": settings.items_per_user,
} | null |
158,262 | from fastapi import FastAPI
from .config import settings
settings = Settings()
async def info():
return {
"app_name": settings.app_name,
"admin_email": settings.admin_email,
"items_per_user": settings.items_per_user,
} | null |
158,263 | from functools import lru_cache
from fastapi import Depends, FastAPI
from .config import Settings
def get_settings():
class Settings(BaseSettings):
async def info(settings: Settings = Depends(get_settings)):
return {
"app_name": settings.app_name,
"admin_email": settings.admin_email,
"items_per_user": settings.items_per_user,
} | null |
158,264 | from typing import Optional
from fastapi import APIRouter, FastAPI
from pydantic import BaseModel, HttpUrl
class InvoiceEvent(BaseModel):
description: str
paid: bool
def invoice_notification(body: InvoiceEvent):
pass | null |
158,265 | from typing import Optional
from fastapi import APIRouter, FastAPI
from pydantic import BaseModel, HttpUrl
class Invoice(BaseModel):
id: str
title: Optional[str] = None
customer: str
total: float
The provided code snippet includes necessary dependencies for implementing the `create_invoice` function. Write a Python function `def create_invoice(invoice: Invoice, callback_url: Optional[HttpUrl] = None)` to solve the following problem:
Create an invoice. This will (let's imagine) let the API user (some external developer) create an invoice. And this path operation will: * Send the invoice to the client. * Collect the money from the client. * Send a notification back to the API user (the external developer), as a callback. * At this point is that the API will somehow send a POST request to the external API with the notification of the invoice event (e.g. "payment successful").
Here is the function:
def create_invoice(invoice: Invoice, callback_url: Optional[HttpUrl] = None):
"""
Create an invoice.
This will (let's imagine) let the API user (some external developer) create an
invoice.
And this path operation will:
* Send the invoice to the client.
* Collect the money from the client.
* Send a notification back to the API user (the external developer), as a callback.
* At this point is that the API will somehow send a POST request to the
external API with the notification of the invoice event
(e.g. "payment successful").
"""
# Send the invoice, collect the money, send the notification (the callback)
return {"msg": "Invoice received"} | Create an invoice. This will (let's imagine) let the API user (some external developer) create an invoice. And this path operation will: * Send the invoice to the client. * Collect the money from the client. * Send a notification back to the API user (the external developer), as a callback. * At this point is that the API will somehow send a POST request to the external API with the notification of the invoice event (e.g. "payment successful"). |
158,266 | from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
items = {
"foo": {"name": "Foo", "price": 50.2},
"bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
"baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
}
async def read_item(item_id: str):
return items[item_id] | null |
158,267 | from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
class Item(BaseModel):
name: str | None = None
description: str | None = None
price: float | None = None
tax: float = 10.5
tags: list[str] = []
items = {
"foo": {"name": "Foo", "price": 50.2},
"bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
"baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
}
def jsonable_encoder(
obj: Any,
include: Optional[Union[SetIntStr, DictIntStrAny]] = None,
exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None,
by_alias: bool = True,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None,
sqlalchemy_safe: bool = True,
) -> Any:
custom_encoder = custom_encoder or {}
if custom_encoder:
if type(obj) in custom_encoder:
return custom_encoder[type(obj)](obj)
else:
for encoder_type, encoder_instance in custom_encoder.items():
if isinstance(obj, encoder_type):
return encoder_instance(obj)
if include is not None and not isinstance(include, (set, dict)):
include = set(include)
if exclude is not None and not isinstance(exclude, (set, dict)):
exclude = set(exclude)
if isinstance(obj, BaseModel):
encoder = getattr(obj.__config__, "json_encoders", {})
if custom_encoder:
encoder.update(custom_encoder)
obj_dict = obj.dict(
include=include, # type: ignore # in Pydantic
exclude=exclude, # type: ignore # in Pydantic
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_none=exclude_none,
exclude_defaults=exclude_defaults,
)
if "__root__" in obj_dict:
obj_dict = obj_dict["__root__"]
return jsonable_encoder(
obj_dict,
exclude_none=exclude_none,
exclude_defaults=exclude_defaults,
custom_encoder=encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
if dataclasses.is_dataclass(obj):
return dataclasses.asdict(obj)
if isinstance(obj, Enum):
return obj.value
if isinstance(obj, PurePath):
return str(obj)
if isinstance(obj, (str, int, float, type(None))):
return obj
if isinstance(obj, dict):
encoded_dict = {}
for key, value in obj.items():
if (
(
not sqlalchemy_safe
or (not isinstance(key, str))
or (not key.startswith("_sa"))
)
and (value is not None or not exclude_none)
and ((include and key in include) or not exclude or key not in exclude)
):
encoded_key = jsonable_encoder(
key,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_none=exclude_none,
custom_encoder=custom_encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
encoded_value = jsonable_encoder(
value,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_none=exclude_none,
custom_encoder=custom_encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
encoded_dict[encoded_key] = encoded_value
return encoded_dict
if isinstance(obj, (list, set, frozenset, GeneratorType, tuple)):
encoded_list = []
for item in obj:
encoded_list.append(
jsonable_encoder(
item,
include=include,
exclude=exclude,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
exclude_none=exclude_none,
custom_encoder=custom_encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
)
return encoded_list
if type(obj) in ENCODERS_BY_TYPE:
return ENCODERS_BY_TYPE[type(obj)](obj)
for encoder, classes_tuple in encoders_by_class_tuples.items():
if isinstance(obj, classes_tuple):
return encoder(obj)
errors: List[Exception] = []
try:
data = dict(obj)
except Exception as e:
errors.append(e)
try:
data = vars(obj)
except Exception as e:
errors.append(e)
raise ValueError(errors)
return jsonable_encoder(
data,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
exclude_none=exclude_none,
custom_encoder=custom_encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
async def update_item(item_id: str, item: Item):
update_item_encoded = jsonable_encoder(item)
items[item_id] = update_item_encoded
return update_item_encoded | null |
158,268 | from typing import List, Optional
from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
items = {
"foo": {"name": "Foo", "price": 50.2},
"bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
"baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
}
async def read_item(item_id: str):
return items[item_id] | null |
158,269 | from typing import List, Optional
from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
class Item(BaseModel):
name: Optional[str] = None
description: Optional[str] = None
price: Optional[float] = None
tax: float = 10.5
tags: List[str] = []
items = {
"foo": {"name": "Foo", "price": 50.2},
"bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
"baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
}
def jsonable_encoder(
obj: Any,
include: Optional[Union[SetIntStr, DictIntStrAny]] = None,
exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None,
by_alias: bool = True,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None,
sqlalchemy_safe: bool = True,
) -> Any:
custom_encoder = custom_encoder or {}
if custom_encoder:
if type(obj) in custom_encoder:
return custom_encoder[type(obj)](obj)
else:
for encoder_type, encoder_instance in custom_encoder.items():
if isinstance(obj, encoder_type):
return encoder_instance(obj)
if include is not None and not isinstance(include, (set, dict)):
include = set(include)
if exclude is not None and not isinstance(exclude, (set, dict)):
exclude = set(exclude)
if isinstance(obj, BaseModel):
encoder = getattr(obj.__config__, "json_encoders", {})
if custom_encoder:
encoder.update(custom_encoder)
obj_dict = obj.dict(
include=include, # type: ignore # in Pydantic
exclude=exclude, # type: ignore # in Pydantic
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_none=exclude_none,
exclude_defaults=exclude_defaults,
)
if "__root__" in obj_dict:
obj_dict = obj_dict["__root__"]
return jsonable_encoder(
obj_dict,
exclude_none=exclude_none,
exclude_defaults=exclude_defaults,
custom_encoder=encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
if dataclasses.is_dataclass(obj):
return dataclasses.asdict(obj)
if isinstance(obj, Enum):
return obj.value
if isinstance(obj, PurePath):
return str(obj)
if isinstance(obj, (str, int, float, type(None))):
return obj
if isinstance(obj, dict):
encoded_dict = {}
for key, value in obj.items():
if (
(
not sqlalchemy_safe
or (not isinstance(key, str))
or (not key.startswith("_sa"))
)
and (value is not None or not exclude_none)
and ((include and key in include) or not exclude or key not in exclude)
):
encoded_key = jsonable_encoder(
key,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_none=exclude_none,
custom_encoder=custom_encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
encoded_value = jsonable_encoder(
value,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_none=exclude_none,
custom_encoder=custom_encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
encoded_dict[encoded_key] = encoded_value
return encoded_dict
if isinstance(obj, (list, set, frozenset, GeneratorType, tuple)):
encoded_list = []
for item in obj:
encoded_list.append(
jsonable_encoder(
item,
include=include,
exclude=exclude,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
exclude_none=exclude_none,
custom_encoder=custom_encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
)
return encoded_list
if type(obj) in ENCODERS_BY_TYPE:
return ENCODERS_BY_TYPE[type(obj)](obj)
for encoder, classes_tuple in encoders_by_class_tuples.items():
if isinstance(obj, classes_tuple):
return encoder(obj)
errors: List[Exception] = []
try:
data = dict(obj)
except Exception as e:
errors.append(e)
try:
data = vars(obj)
except Exception as e:
errors.append(e)
raise ValueError(errors)
return jsonable_encoder(
data,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
exclude_none=exclude_none,
custom_encoder=custom_encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
async def update_item(item_id: str, item: Item):
update_item_encoded = jsonable_encoder(item)
items[item_id] = update_item_encoded
return update_item_encoded | null |
158,270 | from typing import Optional
from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
items = {
"foo": {"name": "Foo", "price": 50.2},
"bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
"baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
}
async def read_item(item_id: str):
return items[item_id] | null |
158,271 | from typing import Optional
from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
class Item(BaseModel):
name: Optional[str] = None
description: Optional[str] = None
price: Optional[float] = None
tax: float = 10.5
tags: list[str] = []
items = {
"foo": {"name": "Foo", "price": 50.2},
"bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
"baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
}
def jsonable_encoder(
obj: Any,
include: Optional[Union[SetIntStr, DictIntStrAny]] = None,
exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None,
by_alias: bool = True,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None,
sqlalchemy_safe: bool = True,
) -> Any:
custom_encoder = custom_encoder or {}
if custom_encoder:
if type(obj) in custom_encoder:
return custom_encoder[type(obj)](obj)
else:
for encoder_type, encoder_instance in custom_encoder.items():
if isinstance(obj, encoder_type):
return encoder_instance(obj)
if include is not None and not isinstance(include, (set, dict)):
include = set(include)
if exclude is not None and not isinstance(exclude, (set, dict)):
exclude = set(exclude)
if isinstance(obj, BaseModel):
encoder = getattr(obj.__config__, "json_encoders", {})
if custom_encoder:
encoder.update(custom_encoder)
obj_dict = obj.dict(
include=include, # type: ignore # in Pydantic
exclude=exclude, # type: ignore # in Pydantic
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_none=exclude_none,
exclude_defaults=exclude_defaults,
)
if "__root__" in obj_dict:
obj_dict = obj_dict["__root__"]
return jsonable_encoder(
obj_dict,
exclude_none=exclude_none,
exclude_defaults=exclude_defaults,
custom_encoder=encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
if dataclasses.is_dataclass(obj):
return dataclasses.asdict(obj)
if isinstance(obj, Enum):
return obj.value
if isinstance(obj, PurePath):
return str(obj)
if isinstance(obj, (str, int, float, type(None))):
return obj
if isinstance(obj, dict):
encoded_dict = {}
for key, value in obj.items():
if (
(
not sqlalchemy_safe
or (not isinstance(key, str))
or (not key.startswith("_sa"))
)
and (value is not None or not exclude_none)
and ((include and key in include) or not exclude or key not in exclude)
):
encoded_key = jsonable_encoder(
key,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_none=exclude_none,
custom_encoder=custom_encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
encoded_value = jsonable_encoder(
value,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_none=exclude_none,
custom_encoder=custom_encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
encoded_dict[encoded_key] = encoded_value
return encoded_dict
if isinstance(obj, (list, set, frozenset, GeneratorType, tuple)):
encoded_list = []
for item in obj:
encoded_list.append(
jsonable_encoder(
item,
include=include,
exclude=exclude,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
exclude_none=exclude_none,
custom_encoder=custom_encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
)
return encoded_list
if type(obj) in ENCODERS_BY_TYPE:
return ENCODERS_BY_TYPE[type(obj)](obj)
for encoder, classes_tuple in encoders_by_class_tuples.items():
if isinstance(obj, classes_tuple):
return encoder(obj)
errors: List[Exception] = []
try:
data = dict(obj)
except Exception as e:
errors.append(e)
try:
data = vars(obj)
except Exception as e:
errors.append(e)
raise ValueError(errors)
return jsonable_encoder(
data,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
exclude_none=exclude_none,
custom_encoder=custom_encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
async def update_item(item_id: str, item: Item):
stored_item_data = items[item_id]
stored_item_model = Item(**stored_item_data)
update_data = item.dict(exclude_unset=True)
updated_item = stored_item_model.copy(update=update_data)
items[item_id] = jsonable_encoder(updated_item)
return updated_item | null |
158,273 | from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
class Item(BaseModel):
name: str | None = None
description: str | None = None
price: float | None = None
tax: float = 10.5
tags: list[str] = []
items = {
"foo": {"name": "Foo", "price": 50.2},
"bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
"baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
}
def jsonable_encoder(
obj: Any,
include: Optional[Union[SetIntStr, DictIntStrAny]] = None,
exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None,
by_alias: bool = True,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None,
sqlalchemy_safe: bool = True,
) -> Any:
custom_encoder = custom_encoder or {}
if custom_encoder:
if type(obj) in custom_encoder:
return custom_encoder[type(obj)](obj)
else:
for encoder_type, encoder_instance in custom_encoder.items():
if isinstance(obj, encoder_type):
return encoder_instance(obj)
if include is not None and not isinstance(include, (set, dict)):
include = set(include)
if exclude is not None and not isinstance(exclude, (set, dict)):
exclude = set(exclude)
if isinstance(obj, BaseModel):
encoder = getattr(obj.__config__, "json_encoders", {})
if custom_encoder:
encoder.update(custom_encoder)
obj_dict = obj.dict(
include=include, # type: ignore # in Pydantic
exclude=exclude, # type: ignore # in Pydantic
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_none=exclude_none,
exclude_defaults=exclude_defaults,
)
if "__root__" in obj_dict:
obj_dict = obj_dict["__root__"]
return jsonable_encoder(
obj_dict,
exclude_none=exclude_none,
exclude_defaults=exclude_defaults,
custom_encoder=encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
if dataclasses.is_dataclass(obj):
return dataclasses.asdict(obj)
if isinstance(obj, Enum):
return obj.value
if isinstance(obj, PurePath):
return str(obj)
if isinstance(obj, (str, int, float, type(None))):
return obj
if isinstance(obj, dict):
encoded_dict = {}
for key, value in obj.items():
if (
(
not sqlalchemy_safe
or (not isinstance(key, str))
or (not key.startswith("_sa"))
)
and (value is not None or not exclude_none)
and ((include and key in include) or not exclude or key not in exclude)
):
encoded_key = jsonable_encoder(
key,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_none=exclude_none,
custom_encoder=custom_encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
encoded_value = jsonable_encoder(
value,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_none=exclude_none,
custom_encoder=custom_encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
encoded_dict[encoded_key] = encoded_value
return encoded_dict
if isinstance(obj, (list, set, frozenset, GeneratorType, tuple)):
encoded_list = []
for item in obj:
encoded_list.append(
jsonable_encoder(
item,
include=include,
exclude=exclude,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
exclude_none=exclude_none,
custom_encoder=custom_encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
)
return encoded_list
if type(obj) in ENCODERS_BY_TYPE:
return ENCODERS_BY_TYPE[type(obj)](obj)
for encoder, classes_tuple in encoders_by_class_tuples.items():
if isinstance(obj, classes_tuple):
return encoder(obj)
errors: List[Exception] = []
try:
data = dict(obj)
except Exception as e:
errors.append(e)
try:
data = vars(obj)
except Exception as e:
errors.append(e)
raise ValueError(errors)
return jsonable_encoder(
data,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
exclude_none=exclude_none,
custom_encoder=custom_encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
async def update_item(item_id: str, item: Item):
stored_item_data = items[item_id]
stored_item_model = Item(**stored_item_data)
update_data = item.dict(exclude_unset=True)
updated_item = stored_item_model.copy(update=update_data)
items[item_id] = jsonable_encoder(updated_item)
return updated_item | null |
158,275 | from typing import Optional
from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
class Item(BaseModel):
items = {
"foo": {"name": "Foo", "price": 50.2},
"bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
"baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
}
def jsonable_encoder(
obj: Any,
include: Optional[Union[SetIntStr, DictIntStrAny]] = None,
exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None,
by_alias: bool = True,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None,
sqlalchemy_safe: bool = True,
) -> Any:
async def update_item(item_id: str, item: Item):
update_item_encoded = jsonable_encoder(item)
items[item_id] = update_item_encoded
return update_item_encoded | null |
158,277 | from typing import List, Optional
from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
class Item(BaseModel):
name: Optional[str] = None
description: Optional[str] = None
price: Optional[float] = None
tax: float = 10.5
tags: List[str] = []
items = {
"foo": {"name": "Foo", "price": 50.2},
"bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
"baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
}
def jsonable_encoder(
obj: Any,
include: Optional[Union[SetIntStr, DictIntStrAny]] = None,
exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None,
by_alias: bool = True,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None,
sqlalchemy_safe: bool = True,
) -> Any:
custom_encoder = custom_encoder or {}
if custom_encoder:
if type(obj) in custom_encoder:
return custom_encoder[type(obj)](obj)
else:
for encoder_type, encoder_instance in custom_encoder.items():
if isinstance(obj, encoder_type):
return encoder_instance(obj)
if include is not None and not isinstance(include, (set, dict)):
include = set(include)
if exclude is not None and not isinstance(exclude, (set, dict)):
exclude = set(exclude)
if isinstance(obj, BaseModel):
encoder = getattr(obj.__config__, "json_encoders", {})
if custom_encoder:
encoder.update(custom_encoder)
obj_dict = obj.dict(
include=include, # type: ignore # in Pydantic
exclude=exclude, # type: ignore # in Pydantic
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_none=exclude_none,
exclude_defaults=exclude_defaults,
)
if "__root__" in obj_dict:
obj_dict = obj_dict["__root__"]
return jsonable_encoder(
obj_dict,
exclude_none=exclude_none,
exclude_defaults=exclude_defaults,
custom_encoder=encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
if dataclasses.is_dataclass(obj):
return dataclasses.asdict(obj)
if isinstance(obj, Enum):
return obj.value
if isinstance(obj, PurePath):
return str(obj)
if isinstance(obj, (str, int, float, type(None))):
return obj
if isinstance(obj, dict):
encoded_dict = {}
for key, value in obj.items():
if (
(
not sqlalchemy_safe
or (not isinstance(key, str))
or (not key.startswith("_sa"))
)
and (value is not None or not exclude_none)
and ((include and key in include) or not exclude or key not in exclude)
):
encoded_key = jsonable_encoder(
key,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_none=exclude_none,
custom_encoder=custom_encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
encoded_value = jsonable_encoder(
value,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_none=exclude_none,
custom_encoder=custom_encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
encoded_dict[encoded_key] = encoded_value
return encoded_dict
if isinstance(obj, (list, set, frozenset, GeneratorType, tuple)):
encoded_list = []
for item in obj:
encoded_list.append(
jsonable_encoder(
item,
include=include,
exclude=exclude,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
exclude_none=exclude_none,
custom_encoder=custom_encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
)
return encoded_list
if type(obj) in ENCODERS_BY_TYPE:
return ENCODERS_BY_TYPE[type(obj)](obj)
for encoder, classes_tuple in encoders_by_class_tuples.items():
if isinstance(obj, classes_tuple):
return encoder(obj)
errors: List[Exception] = []
try:
data = dict(obj)
except Exception as e:
errors.append(e)
try:
data = vars(obj)
except Exception as e:
errors.append(e)
raise ValueError(errors)
return jsonable_encoder(
data,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
exclude_none=exclude_none,
custom_encoder=custom_encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
async def update_item(item_id: str, item: Item):
stored_item_data = items[item_id]
stored_item_model = Item(**stored_item_data)
update_data = item.dict(exclude_unset=True)
updated_item = stored_item_model.copy(update=update_data)
items[item_id] = jsonable_encoder(updated_item)
return updated_item | null |
158,278 | import os
import re
import shutil
from http.server import HTTPServer, SimpleHTTPRequestHandler
from multiprocessing import Pool
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import mkdocs.commands.build
import mkdocs.commands.serve
import mkdocs.config
import mkdocs.utils
import typer
import yaml
from jinja2 import Template
mkdocs_name = "mkdocs.yml"
missing_translation_snippet = """
{!../../../docs/missing-translation.md!}
"""
en_docs_path = Path("docs/en")
def lang_callback(lang: Optional[str]):
if lang is None:
return
if not lang.isalpha() or len(lang) != 2:
typer.echo("Use a 2 letter language code, like: es")
raise typer.Abort()
lang = lang.lower()
return lang
def get_base_lang_config(lang: str):
en_config = get_en_config()
fastapi_url_base = "https://fastapi.tiangolo.com/"
new_config = en_config.copy()
new_config["site_url"] = en_config["site_url"] + f"{lang}/"
new_config["theme"]["logo"] = fastapi_url_base + en_config["theme"]["logo"]
new_config["theme"]["favicon"] = fastapi_url_base + en_config["theme"]["favicon"]
new_config["theme"]["language"] = lang
new_config["nav"] = en_config["nav"][:2]
extra_css = []
css: str
for css in en_config["extra_css"]:
if css.startswith("http"):
extra_css.append(css)
else:
extra_css.append(fastapi_url_base + css)
new_config["extra_css"] = extra_css
extra_js = []
js: str
for js in en_config["extra_javascript"]:
if js.startswith("http"):
extra_js.append(js)
else:
extra_js.append(fastapi_url_base + js)
new_config["extra_javascript"] = extra_js
return new_config
def update_languages(
lang: str = typer.Argument(
None, callback=lang_callback, autocompletion=complete_existing_lang
)
):
"""
Update the mkdocs.yml file Languages section including all the available languages.
The LANG argument is a 2-letter language code. If it's not provided, update all the
mkdocs.yml files (for all the languages).
"""
if lang is None:
for lang_path in get_lang_paths():
if lang_path.is_dir():
update_single_lang(lang_path.name)
else:
update_single_lang(lang)
The provided code snippet includes necessary dependencies for implementing the `new_lang` function. Write a Python function `def new_lang(lang: str = typer.Argument(..., callback=lang_callback))` to solve the following problem:
Generate a new docs translation directory for the language LANG. LANG should be a 2-letter language code, like: en, es, de, pt, etc.
Here is the function:
def new_lang(lang: str = typer.Argument(..., callback=lang_callback)):
"""
Generate a new docs translation directory for the language LANG.
LANG should be a 2-letter language code, like: en, es, de, pt, etc.
"""
new_path: Path = Path("docs") / lang
if new_path.exists():
typer.echo(f"The language was already created: {lang}")
raise typer.Abort()
new_path.mkdir()
new_config = get_base_lang_config(lang)
new_config_path: Path = Path(new_path) / mkdocs_name
new_config_path.write_text(
yaml.dump(new_config, sort_keys=False, width=200, allow_unicode=True),
encoding="utf-8",
)
new_config_docs_path: Path = new_path / "docs"
new_config_docs_path.mkdir()
en_index_path: Path = en_docs_path / "docs" / "index.md"
new_index_path: Path = new_config_docs_path / "index.md"
en_index_content = en_index_path.read_text(encoding="utf-8")
new_index_content = f"{missing_translation_snippet}\n\n{en_index_content}"
new_index_path.write_text(new_index_content, encoding="utf-8")
new_overrides_gitignore_path = new_path / "overrides" / ".gitignore"
new_overrides_gitignore_path.parent.mkdir(parents=True, exist_ok=True)
new_overrides_gitignore_path.write_text("")
typer.secho(f"Successfully initialized: {new_path}", color=typer.colors.GREEN)
update_languages(lang=None) | Generate a new docs translation directory for the language LANG. LANG should be a 2-letter language code, like: en, es, de, pt, etc. |
158,279 | import os
import re
import shutil
from http.server import HTTPServer, SimpleHTTPRequestHandler
from multiprocessing import Pool
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import mkdocs.commands.build
import mkdocs.commands.serve
import mkdocs.config
import mkdocs.utils
import typer
import yaml
from jinja2 import Template
def generate_readme_content():
en_index = en_docs_path / "docs" / "index.md"
content = en_index.read_text("utf-8")
match_start = re.search(r"<!-- sponsors -->", content)
match_end = re.search(r"<!-- /sponsors -->", content)
sponsors_data_path = en_docs_path / "data" / "sponsors.yml"
sponsors = mkdocs.utils.yaml_load(sponsors_data_path.read_text(encoding="utf-8"))
if not (match_start and match_end):
raise RuntimeError("Couldn't auto-generate sponsors section")
pre_end = match_start.end()
post_start = match_end.start()
template = Template(index_sponsors_template)
message = template.render(sponsors=sponsors)
pre_content = content[:pre_end]
post_content = content[post_start:]
new_content = pre_content + message + post_content
return new_content
The provided code snippet includes necessary dependencies for implementing the `generate_readme` function. Write a Python function `def generate_readme()` to solve the following problem:
Generate README.md content from main index.md
Here is the function:
def generate_readme():
"""
Generate README.md content from main index.md
"""
typer.echo("Generating README")
readme_path = Path("README.md")
new_content = generate_readme_content()
readme_path.write_text(new_content, encoding="utf-8") | Generate README.md content from main index.md |
158,280 | import os
import re
import shutil
from http.server import HTTPServer, SimpleHTTPRequestHandler
from multiprocessing import Pool
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import mkdocs.commands.build
import mkdocs.commands.serve
import mkdocs.config
import mkdocs.utils
import typer
import yaml
from jinja2 import Template
def generate_readme_content():
en_index = en_docs_path / "docs" / "index.md"
content = en_index.read_text("utf-8")
match_start = re.search(r"<!-- sponsors -->", content)
match_end = re.search(r"<!-- /sponsors -->", content)
sponsors_data_path = en_docs_path / "data" / "sponsors.yml"
sponsors = mkdocs.utils.yaml_load(sponsors_data_path.read_text(encoding="utf-8"))
if not (match_start and match_end):
raise RuntimeError("Couldn't auto-generate sponsors section")
pre_end = match_start.end()
post_start = match_end.start()
template = Template(index_sponsors_template)
message = template.render(sponsors=sponsors)
pre_content = content[:pre_end]
post_content = content[post_start:]
new_content = pre_content + message + post_content
return new_content
The provided code snippet includes necessary dependencies for implementing the `verify_readme` function. Write a Python function `def verify_readme()` to solve the following problem:
Verify README.md content from main index.md
Here is the function:
def verify_readme():
"""
Verify README.md content from main index.md
"""
typer.echo("Verifying README")
readme_path = Path("README.md")
generated_content = generate_readme_content()
readme_content = readme_path.read_text("utf-8")
if generated_content != readme_content:
typer.secho(
"README.md outdated from the latest index.md", color=typer.colors.RED
)
raise typer.Abort()
typer.echo("Valid README ✅") | Verify README.md content from main index.md |
158,281 | import os
import re
import shutil
from http.server import HTTPServer, SimpleHTTPRequestHandler
from multiprocessing import Pool
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import mkdocs.commands.build
import mkdocs.commands.serve
import mkdocs.config
import mkdocs.utils
import typer
import yaml
from jinja2 import Template
en_docs_path = Path("docs/en")
def get_lang_paths():
return sorted(docs_path.iterdir())
def build_lang(
lang: str = typer.Argument(
..., callback=lang_callback, autocompletion=complete_existing_lang
)
):
"""
Build the docs for a language, filling missing pages with translation notifications.
"""
lang_path: Path = Path("docs") / lang
if not lang_path.is_dir():
typer.echo(f"The language translation doesn't seem to exist yet: {lang}")
raise typer.Abort()
typer.echo(f"Building docs for: {lang}")
build_dir_path = Path("docs_build")
build_dir_path.mkdir(exist_ok=True)
build_lang_path = build_dir_path / lang
en_lang_path = Path("docs/en")
site_path = Path("site").absolute()
if lang == "en":
dist_path = site_path
else:
dist_path: Path = site_path / lang
shutil.rmtree(build_lang_path, ignore_errors=True)
shutil.copytree(lang_path, build_lang_path)
shutil.copytree(en_docs_path / "data", build_lang_path / "data")
overrides_src = en_docs_path / "overrides"
overrides_dest = build_lang_path / "overrides"
for path in overrides_src.iterdir():
dest_path = overrides_dest / path.name
if not dest_path.exists():
shutil.copy(path, dest_path)
en_config_path: Path = en_lang_path / mkdocs_name
en_config: dict = mkdocs.utils.yaml_load(en_config_path.read_text(encoding="utf-8"))
nav = en_config["nav"]
lang_config_path: Path = lang_path / mkdocs_name
lang_config: dict = mkdocs.utils.yaml_load(
lang_config_path.read_text(encoding="utf-8")
)
lang_nav = lang_config["nav"]
# Exclude first 2 entries FastAPI and Languages, for custom handling
use_nav = nav[2:]
lang_use_nav = lang_nav[2:]
file_to_nav = get_file_to_nav_map(use_nav)
sections = get_sections(use_nav)
lang_file_to_nav = get_file_to_nav_map(lang_use_nav)
use_lang_file_to_nav = get_file_to_nav_map(lang_use_nav)
for file in file_to_nav:
file_path = Path(file)
lang_file_path: Path = build_lang_path / "docs" / file_path
en_file_path: Path = en_lang_path / "docs" / file_path
lang_file_path.parent.mkdir(parents=True, exist_ok=True)
if not lang_file_path.is_file():
en_text = en_file_path.read_text(encoding="utf-8")
lang_text = get_text_with_translate_missing(en_text)
lang_file_path.write_text(lang_text, encoding="utf-8")
file_key = file_to_nav[file]
use_lang_file_to_nav[file] = file_key
if file_key:
composite_key = ()
new_key = ()
for key_part in file_key:
composite_key += (key_part,)
key_first_file = sections[composite_key]
if key_first_file in lang_file_to_nav:
new_key = lang_file_to_nav[key_first_file]
else:
new_key += (key_part,)
use_lang_file_to_nav[file] = new_key
key_to_section = {(): []}
for file, orig_file_key in file_to_nav.items():
if file in use_lang_file_to_nav:
file_key = use_lang_file_to_nav[file]
else:
file_key = orig_file_key
section = get_key_section(key_to_section=key_to_section, key=file_key)
section.append(file)
new_nav = key_to_section[()]
export_lang_nav = [lang_nav[0], nav[1]] + new_nav
lang_config["nav"] = export_lang_nav
build_lang_config_path: Path = build_lang_path / mkdocs_name
build_lang_config_path.write_text(
yaml.dump(lang_config, sort_keys=False, width=200, allow_unicode=True),
encoding="utf-8",
)
current_dir = os.getcwd()
os.chdir(build_lang_path)
mkdocs.commands.build.build(mkdocs.config.load_config(site_dir=str(dist_path)))
os.chdir(current_dir)
typer.secho(f"Successfully built docs for: {lang}", color=typer.colors.GREEN)
def update_languages(
lang: str = typer.Argument(
None, callback=lang_callback, autocompletion=complete_existing_lang
)
):
"""
Update the mkdocs.yml file Languages section including all the available languages.
The LANG argument is a 2-letter language code. If it's not provided, update all the
mkdocs.yml files (for all the languages).
"""
if lang is None:
for lang_path in get_lang_paths():
if lang_path.is_dir():
update_single_lang(lang_path.name)
else:
update_single_lang(lang)
The provided code snippet includes necessary dependencies for implementing the `build_all` function. Write a Python function `def build_all()` to solve the following problem:
Build mkdocs site for en, and then build each language inside, end result is located at directory ./site/ with each language inside.
Here is the function:
def build_all():
"""
Build mkdocs site for en, and then build each language inside, end result is located
at directory ./site/ with each language inside.
"""
site_path = Path("site").absolute()
update_languages(lang=None)
current_dir = os.getcwd()
os.chdir(en_docs_path)
typer.echo("Building docs for: en")
mkdocs.commands.build.build(mkdocs.config.load_config(site_dir=str(site_path)))
os.chdir(current_dir)
langs = []
for lang in get_lang_paths():
if lang == en_docs_path or not lang.is_dir():
continue
langs.append(lang.name)
cpu_count = os.cpu_count() or 1
with Pool(cpu_count * 2) as p:
p.map(build_lang, langs) | Build mkdocs site for en, and then build each language inside, end result is located at directory ./site/ with each language inside. |
158,282 | import os
import re
import shutil
from http.server import HTTPServer, SimpleHTTPRequestHandler
from multiprocessing import Pool
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import mkdocs.commands.build
import mkdocs.commands.serve
import mkdocs.config
import mkdocs.utils
import typer
import yaml
from jinja2 import Template
docs_path = Path("docs")
def lang_callback(lang: Optional[str]):
if lang is None:
return
if not lang.isalpha() or len(lang) != 2:
typer.echo("Use a 2 letter language code, like: es")
raise typer.Abort()
lang = lang.lower()
return lang
def complete_existing_lang(incomplete: str):
lang_path: Path
for lang_path in get_lang_paths():
if lang_path.is_dir() and lang_path.name.startswith(incomplete):
yield lang_path.name
def serve():
"""
A quick server to preview a built site with translations.
For development, prefer the command live (or just mkdocs serve).
This is here only to preview a site with translations already built.
Make sure you run the build-all command first.
"""
typer.echo("Warning: this is a very simple server.")
typer.echo("For development, use the command live instead.")
typer.echo("This is here only to preview a site with translations already built.")
typer.echo("Make sure you run the build-all command first.")
os.chdir("site")
server_address = ("", 8008)
server = HTTPServer(server_address, SimpleHTTPRequestHandler)
typer.echo(f"Serving at: http://127.0.0.1:8008")
server.serve_forever()
The provided code snippet includes necessary dependencies for implementing the `live` function. Write a Python function `def live( lang: str = typer.Argument( None, callback=lang_callback, autocompletion=complete_existing_lang ) )` to solve the following problem:
Serve with livereload a docs site for a specific language. This only shows the actual translated files, not the placeholders created with build-all. Takes an optional LANG argument with the name of the language to serve, by default en.
Here is the function:
def live(
lang: str = typer.Argument(
None, callback=lang_callback, autocompletion=complete_existing_lang
)
):
"""
Serve with livereload a docs site for a specific language.
This only shows the actual translated files, not the placeholders created with
build-all.
Takes an optional LANG argument with the name of the language to serve, by default
en.
"""
if lang is None:
lang = "en"
lang_path: Path = docs_path / lang
os.chdir(lang_path)
mkdocs.commands.serve.serve(dev_addr="127.0.0.1:8008") | Serve with livereload a docs site for a specific language. This only shows the actual translated files, not the placeholders created with build-all. Takes an optional LANG argument with the name of the language to serve, by default en. |
158,283 | import inspect
import os
import requests
github_token = os.getenv("GITHUB_TOKEN")
assert github_token
def get_github_graphql(tag_name: str):
def get_github_release_text(tag_name: str):
url = "https://api.github.com/graphql"
headers = {"Authorization": f"Bearer {github_token}"}
github_graphql = get_github_graphql(tag_name=tag_name)
response = requests.post(url, json={"query": github_graphql}, headers=headers)
assert response.status_code == 200
data = response.json()
return data["data"]["repository"]["release"]["description"] | null |
158,284 | import inspect
import os
import requests
tag_name = os.getenv("TAG")
assert tag_name
def get_gitter_message(release_text: str):
text = f"""
New release! :tada: :rocket:
(by FastAPI bot)
## {tag_name}
"""
text = inspect.cleandoc(text) + "\n\n" + release_text
return text | null |
158,285 | import inspect
import os
import requests
room_id = "5c9c9540d73408ce4fbc1403"
gitter_token = os.getenv("GITTER_TOKEN")
assert gitter_token
def send_gitter_message(text: str):
headers = {"Authorization": f"Bearer {gitter_token}"}
url = f"https://api.gitter.im/v1/rooms/{room_id}/chatMessages"
data = {"text": text}
response = requests.post(url, headers=headers, json=data)
assert response.status_code == 200 | null |
158,286 | from pathlib import Path
from sys import argv
from shutil import move
from itertools import chain
GITEA_REPOSITORIES_PATH = 'gitea/repositories'
GITLAB_REPOSITORIES_PATH = 'gitlab/repositories'
def mover(src, dst):
for path in chain(Path(GITEA_REPOSITORIES_PATH).iterdir(), Path(GITLAB_REPOSITORIES_PATH).iterdir()):
if path.is_dir():
dot_git = path / src
try:
move(str(dot_git), str(dot_git.parent / dst))
except FileNotFoundError:
continue | null |
158,287 |
The provided code snippet includes necessary dependencies for implementing the `hello` function. Write a Python function `def hello(name)` to solve the following problem:
This function greets to the person passed in as a parameter
Here is the function:
def hello(name):
"""
This function greets to
the person passed in as
a parameter
"""
return "Hello, " + name | This function greets to the person passed in as a parameter |
158,288 |
The provided code snippet includes necessary dependencies for implementing the `absolute_value` function. Write a Python function `def absolute_value(num)` to solve the following problem:
This function returns the absolute value of the entered number
Here is the function:
def absolute_value(num):
"""This function returns the absolute
value of the entered number"""
if num >= 0:
return num
else:
return -num | This function returns the absolute value of the entered number |
158,289 |
def get_wings_length_of_griffin_based_on_age(age):
if age >= 0 and age < 5:
return 70
elif age >= 5 and age < 10:
return 130
elif age >=10 and age < 25:
return 170 | null |
158,290 |
def my_func():
x = 10
print("Value inside function:",x) | null |
158,291 |
def get_head_weight_of_adult_griffin(age):
return 70 | null |
158,292 |
def gryphon_legacy(n):
# Check if input is 0 then it will
# print incorrect input
if n < 0:
print("Incorrect input")
# Check if n is 0
# then it will return 0
elif n == 0:
return 0
# Check if n is 1,2
# it will return 1
elif n == 1 or n == 2:
return 1
else:
return gryphon_legacy(n-1) + gryphon_legacy(n-2) | null |
158,293 | import hmac
from functools import wraps
from hashlib import sha512
from urllib.parse import urlparse
from urllib.parse import urlunparse
from flask import current_app
from flask import g
from flask import has_request_context
from flask import request
from flask import session
from flask import url_for
from werkzeug.local import LocalProxy
from werkzeug.urls import url_decode
from werkzeug.urls import url_encode
from .config import COOKIE_NAME
from .config import EXEMPT_METHODS
from .signals import user_logged_in
from .signals import user_logged_out
from .signals import user_login_confirmed
def _cookie_digest(payload, key=None):
key = _secret_key(key)
return hmac.new(key, payload.encode("utf-8"), sha512).hexdigest()
The provided code snippet includes necessary dependencies for implementing the `encode_cookie` function. Write a Python function `def encode_cookie(payload, key=None)` to solve the following problem:
This will encode a ``str`` value into a cookie, and sign that cookie with the app's secret key. :param payload: The value to encode, as `str`. :type payload: str :param key: The key to use when creating the cookie digest. If not specified, the SECRET_KEY value from app config will be used. :type key: str
Here is the function:
def encode_cookie(payload, key=None):
"""
This will encode a ``str`` value into a cookie, and sign that cookie
with the app's secret key.
:param payload: The value to encode, as `str`.
:type payload: str
:param key: The key to use when creating the cookie digest. If not
specified, the SECRET_KEY value from app config will be used.
:type key: str
"""
return f"{payload}|{_cookie_digest(payload, key=key)}" | This will encode a ``str`` value into a cookie, and sign that cookie with the app's secret key. :param payload: The value to encode, as `str`. :type payload: str :param key: The key to use when creating the cookie digest. If not specified, the SECRET_KEY value from app config will be used. :type key: str |
158,294 | import hmac
from functools import wraps
from hashlib import sha512
from urllib.parse import urlparse
from urllib.parse import urlunparse
from flask import current_app
from flask import g
from flask import has_request_context
from flask import request
from flask import session
from flask import url_for
from werkzeug.local import LocalProxy
from werkzeug.urls import url_decode
from werkzeug.urls import url_encode
from .config import COOKIE_NAME
from .config import EXEMPT_METHODS
from .signals import user_logged_in
from .signals import user_logged_out
from .signals import user_login_confirmed
def make_next_param(login_url, current_url):
"""
Reduces the scheme and host from a given URL so it can be passed to
the given `login` URL more efficiently.
:param login_url: The login URL being redirected to.
:type login_url: str
:param current_url: The URL to reduce.
:type current_url: str
"""
l_url = urlparse(login_url)
c_url = urlparse(current_url)
if (not l_url.scheme or l_url.scheme == c_url.scheme) and (
not l_url.netloc or l_url.netloc == c_url.netloc
):
return urlunparse(("", "", c_url.path, c_url.params, c_url.query, ""))
return current_url
def expand_login_view(login_view):
"""
Returns the url for the login view, expanding the view name to a url if
needed.
:param login_view: The name of the login view or a URL for the login view.
:type login_view: str
"""
if login_view.startswith(("https://", "http://", "/")):
return login_view
return url_for(login_view)
The provided code snippet includes necessary dependencies for implementing the `login_url` function. Write a Python function `def login_url(login_view, next_url=None, next_field="next")` to solve the following problem:
Creates a URL for redirecting to a login page. If only `login_view` is provided, this will just return the URL for it. If `next_url` is provided, however, this will append a ``next=URL`` parameter to the query string so that the login view can redirect back to that URL. Flask-Login's default unauthorized handler uses this function when redirecting to your login url. To force the host name used, set `FORCE_HOST_FOR_REDIRECTS` to a host. This prevents from redirecting to external sites if request headers Host or X-Forwarded-For are present. :param login_view: The name of the login view. (Alternately, the actual URL to the login view.) :type login_view: str :param next_url: The URL to give the login view for redirection. :type next_url: str :param next_field: What field to store the next URL in. (It defaults to ``next``.) :type next_field: str
Here is the function:
def login_url(login_view, next_url=None, next_field="next"):
"""
Creates a URL for redirecting to a login page. If only `login_view` is
provided, this will just return the URL for it. If `next_url` is provided,
however, this will append a ``next=URL`` parameter to the query string
so that the login view can redirect back to that URL. Flask-Login's default
unauthorized handler uses this function when redirecting to your login url.
To force the host name used, set `FORCE_HOST_FOR_REDIRECTS` to a host. This
prevents from redirecting to external sites if request headers Host or
X-Forwarded-For are present.
:param login_view: The name of the login view. (Alternately, the actual
URL to the login view.)
:type login_view: str
:param next_url: The URL to give the login view for redirection.
:type next_url: str
:param next_field: What field to store the next URL in. (It defaults to
``next``.)
:type next_field: str
"""
base = expand_login_view(login_view)
if next_url is None:
return base
parsed_result = urlparse(base)
md = url_decode(parsed_result.query)
md[next_field] = make_next_param(base, next_url)
netloc = current_app.config.get("FORCE_HOST_FOR_REDIRECTS") or parsed_result.netloc
parsed_result = parsed_result._replace(
netloc=netloc, query=url_encode(md, sort=True)
)
return urlunparse(parsed_result) | Creates a URL for redirecting to a login page. If only `login_view` is provided, this will just return the URL for it. If `next_url` is provided, however, this will append a ``next=URL`` parameter to the query string so that the login view can redirect back to that URL. Flask-Login's default unauthorized handler uses this function when redirecting to your login url. To force the host name used, set `FORCE_HOST_FOR_REDIRECTS` to a host. This prevents from redirecting to external sites if request headers Host or X-Forwarded-For are present. :param login_view: The name of the login view. (Alternately, the actual URL to the login view.) :type login_view: str :param next_url: The URL to give the login view for redirection. :type next_url: str :param next_field: What field to store the next URL in. (It defaults to ``next``.) :type next_field: str |
158,295 | import hmac
from functools import wraps
from hashlib import sha512
from urllib.parse import urlparse
from urllib.parse import urlunparse
from flask import current_app
from flask import g
from flask import has_request_context
from flask import request
from flask import session
from flask import url_for
from werkzeug.local import LocalProxy
from werkzeug.urls import url_decode
from werkzeug.urls import url_encode
from .config import COOKIE_NAME
from .config import EXEMPT_METHODS
from .signals import user_logged_in
from .signals import user_logged_out
from .signals import user_login_confirmed
def decode_cookie(cookie, key=None):
"""
This decodes a cookie given by `encode_cookie`. If verification of the
cookie fails, ``None`` will be implicitly returned.
:param cookie: An encoded cookie.
:type cookie: str
:param key: The key to use when creating the cookie digest. If not
specified, the SECRET_KEY value from app config will be used.
:type key: str
"""
try:
payload, digest = cookie.rsplit("|", 1)
if hasattr(digest, "decode"):
digest = digest.decode("ascii") # pragma: no cover
except ValueError:
return
if hmac.compare_digest(_cookie_digest(payload, key=key), digest):
return payload
COOKIE_NAME = "remember_token"
The provided code snippet includes necessary dependencies for implementing the `login_remembered` function. Write a Python function `def login_remembered()` to solve the following problem:
This returns ``True`` if the current login is remembered across sessions.
Here is the function:
def login_remembered():
"""
This returns ``True`` if the current login is remembered across sessions.
"""
config = current_app.config
cookie_name = config.get("REMEMBER_COOKIE_NAME", COOKIE_NAME)
has_cookie = cookie_name in request.cookies and session.get("_remember") != "clear"
if has_cookie:
cookie = request.cookies[cookie_name]
user_id = decode_cookie(cookie)
return user_id is not None
return False | This returns ``True`` if the current login is remembered across sessions. |
158,296 | import hmac
from functools import wraps
from hashlib import sha512
from urllib.parse import urlparse
from urllib.parse import urlunparse
from flask import current_app
from flask import g
from flask import has_request_context
from flask import request
from flask import session
from flask import url_for
from werkzeug.local import LocalProxy
from werkzeug.urls import url_decode
from werkzeug.urls import url_encode
from .config import COOKIE_NAME
from .config import EXEMPT_METHODS
from .signals import user_logged_in
from .signals import user_logged_out
from .signals import user_login_confirmed
def _get_user():
if has_request_context():
if "_login_user" not in g:
current_app.login_manager._load_user()
return g._login_user
return None
user_logged_in = _signals.signal("logged-in")
The provided code snippet includes necessary dependencies for implementing the `login_user` function. Write a Python function `def login_user(user, remember=False, duration=None, force=False, fresh=True)` to solve the following problem:
Logs a user in. You should pass the actual user object to this. If the user's `is_active` property is ``False``, they will not be logged in unless `force` is ``True``. This will return ``True`` if the log in attempt succeeds, and ``False`` if it fails (i.e. because the user is inactive). :param user: The user object to log in. :type user: object :param remember: Whether to remember the user after their session expires. Defaults to ``False``. :type remember: bool :param duration: The amount of time before the remember cookie expires. If ``None`` the value set in the settings is used. Defaults to ``None``. :type duration: :class:`datetime.timedelta` :param force: If the user is inactive, setting this to ``True`` will log them in regardless. Defaults to ``False``. :type force: bool :param fresh: setting this to ``False`` will log in the user with a session marked as not "fresh". Defaults to ``True``. :type fresh: bool
Here is the function:
def login_user(user, remember=False, duration=None, force=False, fresh=True):
"""
Logs a user in. You should pass the actual user object to this. If the
user's `is_active` property is ``False``, they will not be logged in
unless `force` is ``True``.
This will return ``True`` if the log in attempt succeeds, and ``False`` if
it fails (i.e. because the user is inactive).
:param user: The user object to log in.
:type user: object
:param remember: Whether to remember the user after their session expires.
Defaults to ``False``.
:type remember: bool
:param duration: The amount of time before the remember cookie expires. If
``None`` the value set in the settings is used. Defaults to ``None``.
:type duration: :class:`datetime.timedelta`
:param force: If the user is inactive, setting this to ``True`` will log
them in regardless. Defaults to ``False``.
:type force: bool
:param fresh: setting this to ``False`` will log in the user with a session
marked as not "fresh". Defaults to ``True``.
:type fresh: bool
"""
if not force and not user.is_active:
return False
user_id = getattr(user, current_app.login_manager.id_attribute)()
session["_user_id"] = user_id
session["_fresh"] = fresh
session["_id"] = current_app.login_manager._session_identifier_generator()
if remember:
session["_remember"] = "set"
if duration is not None:
try:
# equal to timedelta.total_seconds() but works with Python 2.6
session["_remember_seconds"] = (
duration.microseconds
+ (duration.seconds + duration.days * 24 * 3600) * 10**6
) / 10.0**6
except AttributeError as e:
raise Exception(
f"duration must be a datetime.timedelta, instead got: {duration}"
) from e
current_app.login_manager._update_request_context_with_user(user)
user_logged_in.send(current_app._get_current_object(), user=_get_user())
return True | Logs a user in. You should pass the actual user object to this. If the user's `is_active` property is ``False``, they will not be logged in unless `force` is ``True``. This will return ``True`` if the log in attempt succeeds, and ``False`` if it fails (i.e. because the user is inactive). :param user: The user object to log in. :type user: object :param remember: Whether to remember the user after their session expires. Defaults to ``False``. :type remember: bool :param duration: The amount of time before the remember cookie expires. If ``None`` the value set in the settings is used. Defaults to ``None``. :type duration: :class:`datetime.timedelta` :param force: If the user is inactive, setting this to ``True`` will log them in regardless. Defaults to ``False``. :type force: bool :param fresh: setting this to ``False`` will log in the user with a session marked as not "fresh". Defaults to ``True``. :type fresh: bool |
158,297 | import hmac
from functools import wraps
from hashlib import sha512
from urllib.parse import urlparse
from urllib.parse import urlunparse
from flask import current_app
from flask import g
from flask import has_request_context
from flask import request
from flask import session
from flask import url_for
from werkzeug.local import LocalProxy
from werkzeug.urls import url_decode
from werkzeug.urls import url_encode
from .config import COOKIE_NAME
from .config import EXEMPT_METHODS
from .signals import user_logged_in
from .signals import user_logged_out
from .signals import user_login_confirmed
def _get_user():
if has_request_context():
if "_login_user" not in g:
current_app.login_manager._load_user()
return g._login_user
return None
COOKIE_NAME = "remember_token"
user_logged_out = _signals.signal("logged-out")
The provided code snippet includes necessary dependencies for implementing the `logout_user` function. Write a Python function `def logout_user()` to solve the following problem:
Logs a user out. (You do not need to pass the actual user.) This will also clean up the remember me cookie if it exists.
Here is the function:
def logout_user():
"""
Logs a user out. (You do not need to pass the actual user.) This will
also clean up the remember me cookie if it exists.
"""
user = _get_user()
if "_user_id" in session:
session.pop("_user_id")
if "_fresh" in session:
session.pop("_fresh")
if "_id" in session:
session.pop("_id")
cookie_name = current_app.config.get("REMEMBER_COOKIE_NAME", COOKIE_NAME)
if cookie_name in request.cookies:
session["_remember"] = "clear"
if "_remember_seconds" in session:
session.pop("_remember_seconds")
user_logged_out.send(current_app._get_current_object(), user=user)
current_app.login_manager._update_request_context_with_user()
return True | Logs a user out. (You do not need to pass the actual user.) This will also clean up the remember me cookie if it exists. |
158,298 | import hmac
from functools import wraps
from hashlib import sha512
from urllib.parse import urlparse
from urllib.parse import urlunparse
from flask import current_app
from flask import g
from flask import has_request_context
from flask import request
from flask import session
from flask import url_for
from werkzeug.local import LocalProxy
from werkzeug.urls import url_decode
from werkzeug.urls import url_encode
from .config import COOKIE_NAME
from .config import EXEMPT_METHODS
from .signals import user_logged_in
from .signals import user_logged_out
from .signals import user_login_confirmed
user_login_confirmed = _signals.signal("login-confirmed")
The provided code snippet includes necessary dependencies for implementing the `confirm_login` function. Write a Python function `def confirm_login()` to solve the following problem:
This sets the current session as fresh. Sessions become stale when they are reloaded from a cookie.
Here is the function:
def confirm_login():
"""
This sets the current session as fresh. Sessions become stale when they
are reloaded from a cookie.
"""
session["_fresh"] = True
session["_id"] = current_app.login_manager._session_identifier_generator()
user_login_confirmed.send(current_app._get_current_object()) | This sets the current session as fresh. Sessions become stale when they are reloaded from a cookie. |
158,299 | import hmac
from functools import wraps
from hashlib import sha512
from urllib.parse import urlparse
from urllib.parse import urlunparse
from flask import current_app
from flask import g
from flask import has_request_context
from flask import request
from flask import session
from flask import url_for
from werkzeug.local import LocalProxy
from werkzeug.urls import url_decode
from werkzeug.urls import url_encode
from .config import COOKIE_NAME
from .config import EXEMPT_METHODS
from .signals import user_logged_in
from .signals import user_logged_out
from .signals import user_login_confirmed
current_user = LocalProxy(lambda: _get_user())
EXEMPT_METHODS = {"OPTIONS"}
The provided code snippet includes necessary dependencies for implementing the `login_required` function. Write a Python function `def login_required(func)` to solve the following problem:
If you decorate a view with this, it will ensure that the current user is logged in and authenticated before calling the actual view. (If they are not, it calls the :attr:`LoginManager.unauthorized` callback.) For example:: @app.route('/post') @login_required def post(): pass If there are only certain times you need to require that your user is logged in, you can do so with:: if not current_user.is_authenticated: return current_app.login_manager.unauthorized() ...which is essentially the code that this function adds to your views. It can be convenient to globally turn off authentication when unit testing. To enable this, if the application configuration variable `LOGIN_DISABLED` is set to `True`, this decorator will be ignored. .. Note :: Per `W3 guidelines for CORS preflight requests <http://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0>`_, HTTP ``OPTIONS`` requests are exempt from login checks. :param func: The view function to decorate. :type func: function
Here is the function:
def login_required(func):
"""
If you decorate a view with this, it will ensure that the current user is
logged in and authenticated before calling the actual view. (If they are
not, it calls the :attr:`LoginManager.unauthorized` callback.) For
example::
@app.route('/post')
@login_required
def post():
pass
If there are only certain times you need to require that your user is
logged in, you can do so with::
if not current_user.is_authenticated:
return current_app.login_manager.unauthorized()
...which is essentially the code that this function adds to your views.
It can be convenient to globally turn off authentication when unit testing.
To enable this, if the application configuration variable `LOGIN_DISABLED`
is set to `True`, this decorator will be ignored.
.. Note ::
Per `W3 guidelines for CORS preflight requests
<http://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0>`_,
HTTP ``OPTIONS`` requests are exempt from login checks.
:param func: The view function to decorate.
:type func: function
"""
@wraps(func)
def decorated_view(*args, **kwargs):
if request.method in EXEMPT_METHODS or current_app.config.get("LOGIN_DISABLED"):
pass
elif not current_user.is_authenticated:
return current_app.login_manager.unauthorized()
# flask 1.x compatibility
# current_app.ensure_sync is only available in Flask >= 2.0
if callable(getattr(current_app, "ensure_sync", None)):
return current_app.ensure_sync(func)(*args, **kwargs)
return func(*args, **kwargs)
return decorated_view | If you decorate a view with this, it will ensure that the current user is logged in and authenticated before calling the actual view. (If they are not, it calls the :attr:`LoginManager.unauthorized` callback.) For example:: @app.route('/post') @login_required def post(): pass If there are only certain times you need to require that your user is logged in, you can do so with:: if not current_user.is_authenticated: return current_app.login_manager.unauthorized() ...which is essentially the code that this function adds to your views. It can be convenient to globally turn off authentication when unit testing. To enable this, if the application configuration variable `LOGIN_DISABLED` is set to `True`, this decorator will be ignored. .. Note :: Per `W3 guidelines for CORS preflight requests <http://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0>`_, HTTP ``OPTIONS`` requests are exempt from login checks. :param func: The view function to decorate. :type func: function |
158,300 | import hmac
from functools import wraps
from hashlib import sha512
from urllib.parse import urlparse
from urllib.parse import urlunparse
from flask import current_app
from flask import g
from flask import has_request_context
from flask import request
from flask import session
from flask import url_for
from werkzeug.local import LocalProxy
from werkzeug.urls import url_decode
from werkzeug.urls import url_encode
from .config import COOKIE_NAME
from .config import EXEMPT_METHODS
from .signals import user_logged_in
from .signals import user_logged_out
from .signals import user_login_confirmed
current_user = LocalProxy(lambda: _get_user())
def login_fresh():
"""
This returns ``True`` if the current login is fresh.
"""
return session.get("_fresh", False)
EXEMPT_METHODS = {"OPTIONS"}
The provided code snippet includes necessary dependencies for implementing the `fresh_login_required` function. Write a Python function `def fresh_login_required(func)` to solve the following problem:
If you decorate a view with this, it will ensure that the current user's login is fresh - i.e. their session was not restored from a 'remember me' cookie. Sensitive operations, like changing a password or e-mail, should be protected with this, to impede the efforts of cookie thieves. If the user is not authenticated, :meth:`LoginManager.unauthorized` is called as normal. If they are authenticated, but their session is not fresh, it will call :meth:`LoginManager.needs_refresh` instead. (In that case, you will need to provide a :attr:`LoginManager.refresh_view`.) Behaves identically to the :func:`login_required` decorator with respect to configuration variables. .. Note :: Per `W3 guidelines for CORS preflight requests <http://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0>`_, HTTP ``OPTIONS`` requests are exempt from login checks. :param func: The view function to decorate. :type func: function
Here is the function:
def fresh_login_required(func):
"""
If you decorate a view with this, it will ensure that the current user's
login is fresh - i.e. their session was not restored from a 'remember me'
cookie. Sensitive operations, like changing a password or e-mail, should
be protected with this, to impede the efforts of cookie thieves.
If the user is not authenticated, :meth:`LoginManager.unauthorized` is
called as normal. If they are authenticated, but their session is not
fresh, it will call :meth:`LoginManager.needs_refresh` instead. (In that
case, you will need to provide a :attr:`LoginManager.refresh_view`.)
Behaves identically to the :func:`login_required` decorator with respect
to configuration variables.
.. Note ::
Per `W3 guidelines for CORS preflight requests
<http://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0>`_,
HTTP ``OPTIONS`` requests are exempt from login checks.
:param func: The view function to decorate.
:type func: function
"""
@wraps(func)
def decorated_view(*args, **kwargs):
if request.method in EXEMPT_METHODS or current_app.config.get("LOGIN_DISABLED"):
pass
elif not current_user.is_authenticated:
return current_app.login_manager.unauthorized()
elif not login_fresh():
return current_app.login_manager.needs_refresh()
try:
# current_app.ensure_sync available in Flask >= 2.0
return current_app.ensure_sync(func)(*args, **kwargs)
except AttributeError: # pragma: no cover
return func(*args, **kwargs)
return decorated_view | If you decorate a view with this, it will ensure that the current user's login is fresh - i.e. their session was not restored from a 'remember me' cookie. Sensitive operations, like changing a password or e-mail, should be protected with this, to impede the efforts of cookie thieves. If the user is not authenticated, :meth:`LoginManager.unauthorized` is called as normal. If they are authenticated, but their session is not fresh, it will call :meth:`LoginManager.needs_refresh` instead. (In that case, you will need to provide a :attr:`LoginManager.refresh_view`.) Behaves identically to the :func:`login_required` decorator with respect to configuration variables. .. Note :: Per `W3 guidelines for CORS preflight requests <http://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0>`_, HTTP ``OPTIONS`` requests are exempt from login checks. :param func: The view function to decorate. :type func: function |
158,301 | import hmac
from functools import wraps
from hashlib import sha512
from urllib.parse import urlparse
from urllib.parse import urlunparse
from flask import current_app
from flask import g
from flask import has_request_context
from flask import request
from flask import session
from flask import url_for
from werkzeug.local import LocalProxy
from werkzeug.urls import url_decode
from werkzeug.urls import url_encode
from .config import COOKIE_NAME
from .config import EXEMPT_METHODS
from .signals import user_logged_in
from .signals import user_logged_out
from .signals import user_login_confirmed
The provided code snippet includes necessary dependencies for implementing the `set_login_view` function. Write a Python function `def set_login_view(login_view, blueprint=None)` to solve the following problem:
Sets the login view for the app or blueprint. If a blueprint is passed, the login view is set for this blueprint on ``blueprint_login_views``. :param login_view: The user object to log in. :type login_view: str :param blueprint: The blueprint which this login view should be set on. Defaults to ``None``. :type blueprint: object
Here is the function:
def set_login_view(login_view, blueprint=None):
"""
Sets the login view for the app or blueprint. If a blueprint is passed,
the login view is set for this blueprint on ``blueprint_login_views``.
:param login_view: The user object to log in.
:type login_view: str
:param blueprint: The blueprint which this login view should be set on.
Defaults to ``None``.
:type blueprint: object
"""
num_login_views = len(current_app.login_manager.blueprint_login_views)
if blueprint is not None or num_login_views != 0:
(current_app.login_manager.blueprint_login_views[blueprint.name]) = login_view
if (
current_app.login_manager.login_view is not None
and None not in current_app.login_manager.blueprint_login_views
):
(
current_app.login_manager.blueprint_login_views[None]
) = current_app.login_manager.login_view
current_app.login_manager.login_view = None
else:
current_app.login_manager.login_view = login_view | Sets the login view for the app or blueprint. If a blueprint is passed, the login view is set for this blueprint on ``blueprint_login_views``. :param login_view: The user object to log in. :type login_view: str :param blueprint: The blueprint which this login view should be set on. Defaults to ``None``. :type blueprint: object |
158,302 | import hmac
from functools import wraps
from hashlib import sha512
from urllib.parse import urlparse
from urllib.parse import urlunparse
from flask import current_app
from flask import g
from flask import has_request_context
from flask import request
from flask import session
from flask import url_for
from werkzeug.local import LocalProxy
from werkzeug.urls import url_decode
from werkzeug.urls import url_encode
from .config import COOKIE_NAME
from .config import EXEMPT_METHODS
from .signals import user_logged_in
from .signals import user_logged_out
from .signals import user_login_confirmed
def _get_remote_addr():
address = request.headers.get("X-Forwarded-For", request.remote_addr)
if address is not None:
# An 'X-Forwarded-For' header includes a comma separated list of the
# addresses, the first address being the actual remote address.
address = address.encode("utf-8").split(b",")[0].strip()
return address
def _create_identifier():
user_agent = request.headers.get("User-Agent")
if user_agent is not None:
user_agent = user_agent.encode("utf-8")
base = f"{_get_remote_addr()}|{user_agent}"
if str is bytes:
base = str(base, "utf-8", errors="replace") # pragma: no cover
h = sha512()
h.update(base.encode("utf8"))
return h.hexdigest() | null |
158,303 | import hmac
from functools import wraps
from hashlib import sha512
from urllib.parse import urlparse
from urllib.parse import urlunparse
from flask import current_app
from flask import g
from flask import has_request_context
from flask import request
from flask import session
from flask import url_for
from werkzeug.local import LocalProxy
from werkzeug.urls import url_decode
from werkzeug.urls import url_encode
from .config import COOKIE_NAME
from .config import EXEMPT_METHODS
from .signals import user_logged_in
from .signals import user_logged_out
from .signals import user_login_confirmed
current_user = LocalProxy(lambda: _get_user())
def _get_user():
if has_request_context():
if "_login_user" not in g:
current_app.login_manager._load_user()
return g._login_user
return None
def _user_context_processor():
return dict(current_user=_get_user()) | null |
158,304 | import flask
import flask_login
import os
users = {'foo@bar.tld': {'password': 'secret'}}
class User(flask_login.UserMixin):
pass
def user_loader(email):
if email not in users:
return
user = User()
user.id = email
return user | null |
158,305 | import flask
import flask_login
import os
users = {'foo@bar.tld': {'password': 'secret'}}
class User(flask_login.UserMixin):
pass
def request_loader(request):
email = request.form.get('email')
if email not in users:
return
user = User()
user.id = email
return user | null |
158,306 | import flask
import flask_login
import os
users = {'foo@bar.tld': {'password': 'secret'}}
class User(flask_login.UserMixin):
def login():
if flask.request.method == 'GET':
return '''
<form action='login' method='POST'>
<input type='text' name='email' id='email' placeholder='email'/>
<input type='password' name='password' id='password' placeholder='password'/>
<input type='submit' name='submit'/>
</form>
'''
email = flask.request.form['email']
if email in users and flask.request.form['password'] == users[email]['password']:
user = User()
user.id = email
flask_login.login_user(user)
return flask.redirect(flask.url_for('protected'))
return 'Bad login' | null |
158,307 | import flask
import flask_login
import os
def protected():
return 'Logged in as: ' + flask_login.current_user.id | null |
158,308 | import flask
import flask_login
import os
def logout():
flask_login.logout_user()
return 'Logged out' | null |
158,309 | import flask
import flask_login
import os
def unauthorized_handler():
return 'Unauthorized', 401 | null |
158,310 | from flask import Flask, redirect, url_for, render_template, request, make_response
from flask import send_from_directory
from pygryphon import greet
def index():
return render_template('index.html') | null |
158,311 | from flask import Flask, redirect, url_for, render_template, request, make_response
from flask import send_from_directory
from pygryphon import greet
def hello():
return greet.hello('User') | null |
158,312 | from flask import Flask, redirect, url_for, render_template, request, make_response
from flask import send_from_directory
from pygryphon import greet
def serving_files():
return send_from_directory('static', 'gryphon.png') | null |
158,313 | import numpy as np
import matplotlib as mpl
from matplotlib import gridspec
import matplotlib.pyplot as plt
from scipy.cluster import hierarchy
import seaborn as sns
import pandas as pd
from .utils import nullity_filter, nullity_sort
import warnings
def nullity_sort(df, sort=None, axis='columns'):
"""
Sorts a DataFrame according to its nullity, in either ascending or descending order.
:param df: The DataFrame object being sorted.
:param sort: The sorting method: either "ascending", "descending", or None (default).
:return: The nullity-sorted DataFrame.
"""
if sort is None:
return df
elif sort not in ['ascending', 'descending']:
raise ValueError('The "sort" parameter must be set to "ascending" or "descending".')
if axis not in ['rows', 'columns']:
raise ValueError('The "axis" parameter must be set to "rows" or "columns".')
if axis == 'columns':
if sort == 'ascending':
return df.iloc[np.argsort(df.count(axis='columns').values), :]
elif sort == 'descending':
return df.iloc[np.flipud(np.argsort(df.count(axis='columns').values)), :]
elif axis == 'rows':
if sort == 'ascending':
return df.iloc[:, np.argsort(df.count(axis='rows').values)]
elif sort == 'descending':
return df.iloc[:, np.flipud(np.argsort(df.count(axis='rows').values))]
def nullity_filter(df, filter=None, p=0, n=0):
"""
Filters a DataFrame according to its nullity, using some combination of 'top' and 'bottom' numerical and
percentage values. Percentages and numerical thresholds can be specified simultaneously: for example,
to get a DataFrame with columns of at least 75% completeness but with no more than 5 columns, use
`nullity_filter(df, filter='top', p=.75, n=5)`.
:param df: The DataFrame whose columns are being filtered.
:param filter: The orientation of the filter being applied to the DataFrame. One of, "top", "bottom",
or None (default). The filter will simply return the DataFrame if you leave the filter argument unspecified or
as None.
:param p: A completeness ratio cut-off. If non-zero the filter will limit the DataFrame to columns with at least p
completeness. Input should be in the range [0, 1].
:param n: A numerical cut-off. If non-zero no more than this number of columns will be returned.
:return: The nullity-filtered `DataFrame`.
"""
if filter == 'top':
if p:
df = df.iloc[:, [c >= p for c in df.count(axis='rows').values / len(df)]]
if n:
df = df.iloc[:, np.sort(np.argsort(df.count(axis='rows').values)[-n:])]
elif filter == 'bottom':
if p:
df = df.iloc[:, [c <= p for c in df.count(axis='rows').values / len(df)]]
if n:
df = df.iloc[:, np.sort(np.argsort(df.count(axis='rows').values)[:n])]
return df
The provided code snippet includes necessary dependencies for implementing the `matrix` function. Write a Python function `def matrix( df, filter=None, n=0, p=0, sort=None, figsize=(25, 10), width_ratios=(15, 1), color=(0.25, 0.25, 0.25), fontsize=16, labels=None, label_rotation=45, sparkline=True, freq=None, ax=None )` to solve the following problem:
A matrix visualization of the nullity of the given DataFrame. :param df: The `DataFrame` being mapped. :param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). :param n: The max number of columns to include in the filtered DataFrame. :param p: The max percentage fill of the columns in the filtered DataFrame. :param sort: The row sort order to apply. Can be "ascending", "descending", or None. :param figsize: The size of the figure to display. :param fontsize: The figure's font size. Default to 16. :param labels: Whether or not to display the column names. Defaults to the underlying data labels when there are 50 columns or less, and no labels when there are more than 50 columns. :param label_rotation: What angle to rotate the text labels to. Defaults to 45 degrees. :param sparkline: Whether or not to display the sparkline. Defaults to True. :param width_ratios: The ratio of the width of the matrix to the width of the sparkline. Defaults to `(15, 1)`. Does nothing if `sparkline=False`. :param color: The color of the filled columns. Default is `(0.25, 0.25, 0.25)`. :return: The plot axis.
Here is the function:
def matrix(
df, filter=None, n=0, p=0, sort=None, figsize=(25, 10), width_ratios=(15, 1),
color=(0.25, 0.25, 0.25), fontsize=16, labels=None, label_rotation=45, sparkline=True,
freq=None, ax=None
):
"""
A matrix visualization of the nullity of the given DataFrame.
:param df: The `DataFrame` being mapped.
:param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default).
:param n: The max number of columns to include in the filtered DataFrame.
:param p: The max percentage fill of the columns in the filtered DataFrame.
:param sort: The row sort order to apply. Can be "ascending", "descending", or None.
:param figsize: The size of the figure to display.
:param fontsize: The figure's font size. Default to 16.
:param labels: Whether or not to display the column names. Defaults to the underlying data labels when there are
50 columns or less, and no labels when there are more than 50 columns.
:param label_rotation: What angle to rotate the text labels to. Defaults to 45 degrees.
:param sparkline: Whether or not to display the sparkline. Defaults to True.
:param width_ratios: The ratio of the width of the matrix to the width of the sparkline. Defaults to `(15, 1)`.
Does nothing if `sparkline=False`.
:param color: The color of the filled columns. Default is `(0.25, 0.25, 0.25)`.
:return: The plot axis.
"""
df = nullity_filter(df, filter=filter, n=n, p=p)
df = nullity_sort(df, sort=sort, axis='columns')
height = df.shape[0]
width = df.shape[1]
# z is the color-mask array, g is a NxNx3 matrix. Apply the z color-mask to set the RGB of each pixel.
z = df.notnull().values
g = np.zeros((height, width, 3), dtype=np.float32)
g[z < 0.5] = [1, 1, 1]
g[z > 0.5] = color
# Set up the matplotlib grid layout. A unary subplot if no sparkline, a left-right splot if yes sparkline.
if ax is None:
plt.figure(figsize=figsize)
if sparkline:
gs = gridspec.GridSpec(1, 2, width_ratios=width_ratios)
gs.update(wspace=0.08)
ax1 = plt.subplot(gs[1])
else:
gs = gridspec.GridSpec(1, 1)
ax0 = plt.subplot(gs[0])
else:
if sparkline is not False:
warnings.warn(
"Plotting a sparkline on an existing axis is not currently supported. "
"To remove this warning, set sparkline=False."
)
sparkline = False
ax0 = ax
# Create the nullity plot.
ax0.imshow(g, interpolation='none')
# Remove extraneous default visual elements.
ax0.set_aspect('auto')
ax0.grid(b=False)
ax0.xaxis.tick_top()
ax0.xaxis.set_ticks_position('none')
ax0.yaxis.set_ticks_position('none')
ax0.spines['top'].set_visible(False)
ax0.spines['right'].set_visible(False)
ax0.spines['bottom'].set_visible(False)
ax0.spines['left'].set_visible(False)
# Set up and rotate the column ticks. The labels argument is set to None by default. If the user specifies it in
# the argument, respect that specification. Otherwise display for <= 50 columns and do not display for > 50.
if labels or (labels is None and len(df.columns) <= 50):
ha = 'left'
ax0.set_xticks(list(range(0, width)))
ax0.set_xticklabels(list(df.columns), rotation=label_rotation, ha=ha, fontsize=fontsize)
else:
ax0.set_xticks([])
# Adds Timestamps ticks if freq is not None, else set up the two top-bottom row ticks.
if freq:
ts_list = []
if type(df.index) == pd.PeriodIndex:
ts_array = pd.date_range(df.index.to_timestamp().date[0],
df.index.to_timestamp().date[-1],
freq=freq).values
ts_ticks = pd.date_range(df.index.to_timestamp().date[0],
df.index.to_timestamp().date[-1],
freq=freq).map(lambda t:
t.strftime('%Y-%m-%d'))
elif type(df.index) == pd.DatetimeIndex:
ts_array = pd.date_range(df.index[0], df.index[-1],
freq=freq).values
ts_ticks = pd.date_range(df.index[0], df.index[-1],
freq=freq).map(lambda t:
t.strftime('%Y-%m-%d'))
else:
raise KeyError('Dataframe index must be PeriodIndex or DatetimeIndex.')
try:
for value in ts_array:
ts_list.append(df.index.get_loc(value))
except KeyError:
raise KeyError('Could not divide time index into desired frequency.')
ax0.set_yticks(ts_list)
ax0.set_yticklabels(ts_ticks, fontsize=int(fontsize / 16 * 20), rotation=0)
else:
ax0.set_yticks([0, df.shape[0] - 1])
ax0.set_yticklabels([1, df.shape[0]], fontsize=int(fontsize / 16 * 20), rotation=0)
# Create the inter-column vertical grid.
in_between_point = [x + 0.5 for x in range(0, width - 1)]
for in_between_point in in_between_point:
ax0.axvline(in_between_point, linestyle='-', color='white')
if sparkline:
# Calculate row-wise completeness for the sparkline.
completeness_srs = df.notnull().astype(bool).sum(axis=1)
x_domain = list(range(0, height))
y_range = list(reversed(completeness_srs.values))
min_completeness = min(y_range)
max_completeness = max(y_range)
min_completeness_index = y_range.index(min_completeness)
max_completeness_index = y_range.index(max_completeness)
# Set up the sparkline, remove the border element.
ax1.grid(b=False)
ax1.set_aspect('auto')
# GH 25
if int(mpl.__version__[0]) <= 1:
ax1.set_axis_bgcolor((1, 1, 1))
else:
ax1.set_facecolor((1, 1, 1))
ax1.spines['top'].set_visible(False)
ax1.spines['right'].set_visible(False)
ax1.spines['bottom'].set_visible(False)
ax1.spines['left'].set_visible(False)
ax1.set_ymargin(0)
# Plot sparkline---plot is sideways so the x and y axis are reversed.
ax1.plot(y_range, x_domain, color=color)
if labels:
# Figure out what case to display the label in: mixed, upper, lower.
label = 'Data Completeness'
if str(df.columns[0]).islower():
label = label.lower()
if str(df.columns[0]).isupper():
label = label.upper()
# Set up and rotate the sparkline label.
ha = 'left'
ax1.set_xticks([min_completeness + (max_completeness - min_completeness) / 2])
ax1.set_xticklabels([label], rotation=label_rotation, ha=ha, fontsize=fontsize)
ax1.xaxis.tick_top()
ax1.set_yticks([])
else:
ax1.set_xticks([])
ax1.set_yticks([])
# Add maximum and minimum labels, circles.
ax1.annotate(max_completeness,
xy=(max_completeness, max_completeness_index),
xytext=(max_completeness + 2, max_completeness_index),
fontsize=int(fontsize / 16 * 14),
va='center',
ha='left')
ax1.annotate(min_completeness,
xy=(min_completeness, min_completeness_index),
xytext=(min_completeness - 2, min_completeness_index),
fontsize=int(fontsize / 16 * 14),
va='center',
ha='right')
ax1.set_xlim([min_completeness - 2, max_completeness + 2]) # Otherwise the circles are cut off.
ax1.plot([min_completeness], [min_completeness_index], '.', color=color, markersize=10.0)
ax1.plot([max_completeness], [max_completeness_index], '.', color=color, markersize=10.0)
# Remove tick mark (only works after plotting).
ax1.xaxis.set_ticks_position('none')
return ax0 | A matrix visualization of the nullity of the given DataFrame. :param df: The `DataFrame` being mapped. :param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). :param n: The max number of columns to include in the filtered DataFrame. :param p: The max percentage fill of the columns in the filtered DataFrame. :param sort: The row sort order to apply. Can be "ascending", "descending", or None. :param figsize: The size of the figure to display. :param fontsize: The figure's font size. Default to 16. :param labels: Whether or not to display the column names. Defaults to the underlying data labels when there are 50 columns or less, and no labels when there are more than 50 columns. :param label_rotation: What angle to rotate the text labels to. Defaults to 45 degrees. :param sparkline: Whether or not to display the sparkline. Defaults to True. :param width_ratios: The ratio of the width of the matrix to the width of the sparkline. Defaults to `(15, 1)`. Does nothing if `sparkline=False`. :param color: The color of the filled columns. Default is `(0.25, 0.25, 0.25)`. :return: The plot axis. |
158,314 | import numpy as np
import matplotlib as mpl
from matplotlib import gridspec
import matplotlib.pyplot as plt
from scipy.cluster import hierarchy
import seaborn as sns
import pandas as pd
from .utils import nullity_filter, nullity_sort
import warnings
def nullity_sort(df, sort=None, axis='columns'):
"""
Sorts a DataFrame according to its nullity, in either ascending or descending order.
:param df: The DataFrame object being sorted.
:param sort: The sorting method: either "ascending", "descending", or None (default).
:return: The nullity-sorted DataFrame.
"""
if sort is None:
return df
elif sort not in ['ascending', 'descending']:
raise ValueError('The "sort" parameter must be set to "ascending" or "descending".')
if axis not in ['rows', 'columns']:
raise ValueError('The "axis" parameter must be set to "rows" or "columns".')
if axis == 'columns':
if sort == 'ascending':
return df.iloc[np.argsort(df.count(axis='columns').values), :]
elif sort == 'descending':
return df.iloc[np.flipud(np.argsort(df.count(axis='columns').values)), :]
elif axis == 'rows':
if sort == 'ascending':
return df.iloc[:, np.argsort(df.count(axis='rows').values)]
elif sort == 'descending':
return df.iloc[:, np.flipud(np.argsort(df.count(axis='rows').values))]
def nullity_filter(df, filter=None, p=0, n=0):
"""
Filters a DataFrame according to its nullity, using some combination of 'top' and 'bottom' numerical and
percentage values. Percentages and numerical thresholds can be specified simultaneously: for example,
to get a DataFrame with columns of at least 75% completeness but with no more than 5 columns, use
`nullity_filter(df, filter='top', p=.75, n=5)`.
:param df: The DataFrame whose columns are being filtered.
:param filter: The orientation of the filter being applied to the DataFrame. One of, "top", "bottom",
or None (default). The filter will simply return the DataFrame if you leave the filter argument unspecified or
as None.
:param p: A completeness ratio cut-off. If non-zero the filter will limit the DataFrame to columns with at least p
completeness. Input should be in the range [0, 1].
:param n: A numerical cut-off. If non-zero no more than this number of columns will be returned.
:return: The nullity-filtered `DataFrame`.
"""
if filter == 'top':
if p:
df = df.iloc[:, [c >= p for c in df.count(axis='rows').values / len(df)]]
if n:
df = df.iloc[:, np.sort(np.argsort(df.count(axis='rows').values)[-n:])]
elif filter == 'bottom':
if p:
df = df.iloc[:, [c <= p for c in df.count(axis='rows').values / len(df)]]
if n:
df = df.iloc[:, np.sort(np.argsort(df.count(axis='rows').values)[:n])]
return df
The provided code snippet includes necessary dependencies for implementing the `bar` function. Write a Python function `def bar( df, figsize=None, fontsize=16, labels=None, label_rotation=45, log=False, color='dimgray', filter=None, n=0, p=0, sort=None, ax=None, orientation=None )` to solve the following problem:
A bar chart visualization of the nullity of the given DataFrame. :param df: The input DataFrame. :param log: Whether or not to display a logarithmic plot. Defaults to False (linear). :param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). :param n: The cap on the number of columns to include in the filtered DataFrame. :param p: The cap on the percentage fill of the columns in the filtered DataFrame. :param sort: The column sort order to apply. Can be "ascending", "descending", or None. :param figsize: The size of the figure to display. :param fontsize: The figure's font size. This default to 16. :param labels: Whether or not to display the column names. Would need to be turned off on particularly large displays. Defaults to True. :param label_rotation: What angle to rotate the text labels to. Defaults to 45 degrees. :param color: The color of the filled columns. Default to the RGB multiple `(0.25, 0.25, 0.25)`. :param orientation: The way the bar plot is oriented. Defaults to vertical if there are less than or equal to 50 columns and horizontal if there are more. :return: The plot axis.
Here is the function:
def bar(
df, figsize=None, fontsize=16, labels=None, label_rotation=45, log=False, color='dimgray',
filter=None, n=0, p=0, sort=None, ax=None, orientation=None
):
"""
A bar chart visualization of the nullity of the given DataFrame.
:param df: The input DataFrame.
:param log: Whether or not to display a logarithmic plot. Defaults to False (linear).
:param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default).
:param n: The cap on the number of columns to include in the filtered DataFrame.
:param p: The cap on the percentage fill of the columns in the filtered DataFrame.
:param sort: The column sort order to apply. Can be "ascending", "descending", or None.
:param figsize: The size of the figure to display.
:param fontsize: The figure's font size. This default to 16.
:param labels: Whether or not to display the column names. Would need to be turned off on particularly large
displays. Defaults to True.
:param label_rotation: What angle to rotate the text labels to. Defaults to 45 degrees.
:param color: The color of the filled columns. Default to the RGB multiple `(0.25, 0.25, 0.25)`.
:param orientation: The way the bar plot is oriented. Defaults to vertical if there are less than or equal to 50
columns and horizontal if there are more.
:return: The plot axis.
"""
df = nullity_filter(df, filter=filter, n=n, p=p)
df = nullity_sort(df, sort=sort, axis='rows')
nullity_counts = len(df) - df.isnull().sum()
if orientation is None:
if len(df.columns) > 50:
orientation = 'left'
else:
orientation = 'bottom'
if ax is None:
ax1 = plt.gca()
if figsize is None:
if len(df.columns) <= 50 or orientation == 'top' or orientation == 'bottom':
figsize = (25, 10)
else:
figsize = (25, (25 + len(df.columns) - 50) * 0.5)
else:
ax1 = ax
figsize = None # for behavioral consistency with other plot types, re-use the given size
plot_args = {'figsize': figsize, 'fontsize': fontsize, 'log': log, 'color': color, 'ax': ax1}
if orientation == 'bottom':
(nullity_counts / len(df)).plot.bar(**plot_args)
else:
(nullity_counts / len(df)).plot.barh(**plot_args)
axes = [ax1]
# Start appending elements, starting with a modified bottom x axis.
if labels or (labels is None and len(df.columns) <= 50):
ax1.set_xticklabels(
ax1.get_xticklabels(), rotation=label_rotation, ha='right', fontsize=fontsize
)
# Create the numerical ticks.
ax2 = ax1.twinx()
axes.append(ax2)
if not log:
ax1.set_ylim([0, 1])
ax2.set_yticks(ax1.get_yticks())
ax2.set_yticklabels([int(n * len(df)) for n in ax1.get_yticks()], fontsize=fontsize)
else:
# For some reason when a logarithmic plot is specified `ax1` always contains two more ticks than actually
# appears in the plot. The fix is to ignore the first and last entries. Also note that when a log scale
# is used, we have to make it match the `ax1` layout ourselves.
ax2.set_yscale('log')
ax2.set_ylim(ax1.get_ylim())
ax2.set_yticklabels([int(n * len(df)) for n in ax1.get_yticks()], fontsize=fontsize)
# Create the third axis, which displays columnar totals above the rest of the plot.
ax3 = ax1.twiny()
axes.append(ax3)
ax3.set_xticks(ax1.get_xticks())
ax3.set_xlim(ax1.get_xlim())
ax3.set_xticklabels(
nullity_counts.values, fontsize=fontsize, rotation=label_rotation, ha='left'
)
else:
# Create the numerical ticks.
ax2 = ax1.twinx()
axes.append(ax2)
if not log:
# Width
ax1.set_xlim([0, 1])
# Bottom
ax2.set_xticks(ax1.get_xticks())
ax2.set_xticklabels([int(n * len(df)) for n in ax1.get_xticks()], fontsize=fontsize)
# Right
ax2.set_yticks(ax1.get_yticks())
ax2.set_yticklabels(nullity_counts.values, fontsize=fontsize, ha='left')
else:
# For some reason when a logarithmic plot is specified `ax1` always contains two more ticks than actually
# appears in the plot. The fix is to ignore the first and last entries. Also note that when a log scale
# is used, we have to make it match the `ax1` layout ourselves.
ax1.set_xscale('log')
ax1.set_xlim(ax1.get_xlim())
# Bottom
ax2.set_xticks(ax1.get_xticks())
ax2.set_xticklabels([int(n * len(df)) for n in ax1.get_xticks()], fontsize=fontsize)
# Right
ax2.set_yticks(ax1.get_yticks())
ax2.set_yticklabels(nullity_counts.values, fontsize=fontsize, ha='left')
# Create the third axis, which displays columnar totals above the rest of the plot.
ax3 = ax1.twiny()
axes.append(ax3)
ax3.set_yticks(ax1.get_yticks())
if log:
ax3.set_xscale('log')
ax3.set_xlim(ax1.get_xlim())
ax3.set_ylim(ax1.get_ylim())
ax3.grid(False)
for ax in axes:
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.xaxis.set_ticks_position('none')
ax.yaxis.set_ticks_position('none')
return ax1 | A bar chart visualization of the nullity of the given DataFrame. :param df: The input DataFrame. :param log: Whether or not to display a logarithmic plot. Defaults to False (linear). :param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). :param n: The cap on the number of columns to include in the filtered DataFrame. :param p: The cap on the percentage fill of the columns in the filtered DataFrame. :param sort: The column sort order to apply. Can be "ascending", "descending", or None. :param figsize: The size of the figure to display. :param fontsize: The figure's font size. This default to 16. :param labels: Whether or not to display the column names. Would need to be turned off on particularly large displays. Defaults to True. :param label_rotation: What angle to rotate the text labels to. Defaults to 45 degrees. :param color: The color of the filled columns. Default to the RGB multiple `(0.25, 0.25, 0.25)`. :param orientation: The way the bar plot is oriented. Defaults to vertical if there are less than or equal to 50 columns and horizontal if there are more. :return: The plot axis. |
158,315 | import numpy as np
import matplotlib as mpl
from matplotlib import gridspec
import matplotlib.pyplot as plt
from scipy.cluster import hierarchy
import seaborn as sns
import pandas as pd
from .utils import nullity_filter, nullity_sort
import warnings
def nullity_sort(df, sort=None, axis='columns'):
"""
Sorts a DataFrame according to its nullity, in either ascending or descending order.
:param df: The DataFrame object being sorted.
:param sort: The sorting method: either "ascending", "descending", or None (default).
:return: The nullity-sorted DataFrame.
"""
if sort is None:
return df
elif sort not in ['ascending', 'descending']:
raise ValueError('The "sort" parameter must be set to "ascending" or "descending".')
if axis not in ['rows', 'columns']:
raise ValueError('The "axis" parameter must be set to "rows" or "columns".')
if axis == 'columns':
if sort == 'ascending':
return df.iloc[np.argsort(df.count(axis='columns').values), :]
elif sort == 'descending':
return df.iloc[np.flipud(np.argsort(df.count(axis='columns').values)), :]
elif axis == 'rows':
if sort == 'ascending':
return df.iloc[:, np.argsort(df.count(axis='rows').values)]
elif sort == 'descending':
return df.iloc[:, np.flipud(np.argsort(df.count(axis='rows').values))]
def nullity_filter(df, filter=None, p=0, n=0):
"""
Filters a DataFrame according to its nullity, using some combination of 'top' and 'bottom' numerical and
percentage values. Percentages and numerical thresholds can be specified simultaneously: for example,
to get a DataFrame with columns of at least 75% completeness but with no more than 5 columns, use
`nullity_filter(df, filter='top', p=.75, n=5)`.
:param df: The DataFrame whose columns are being filtered.
:param filter: The orientation of the filter being applied to the DataFrame. One of, "top", "bottom",
or None (default). The filter will simply return the DataFrame if you leave the filter argument unspecified or
as None.
:param p: A completeness ratio cut-off. If non-zero the filter will limit the DataFrame to columns with at least p
completeness. Input should be in the range [0, 1].
:param n: A numerical cut-off. If non-zero no more than this number of columns will be returned.
:return: The nullity-filtered `DataFrame`.
"""
if filter == 'top':
if p:
df = df.iloc[:, [c >= p for c in df.count(axis='rows').values / len(df)]]
if n:
df = df.iloc[:, np.sort(np.argsort(df.count(axis='rows').values)[-n:])]
elif filter == 'bottom':
if p:
df = df.iloc[:, [c <= p for c in df.count(axis='rows').values / len(df)]]
if n:
df = df.iloc[:, np.sort(np.argsort(df.count(axis='rows').values)[:n])]
return df
The provided code snippet includes necessary dependencies for implementing the `heatmap` function. Write a Python function `def heatmap( df, filter=None, n=0, p=0, sort=None, figsize=(20, 12), fontsize=16, labels=True, label_rotation=45, cmap='RdBu', vmin=-1, vmax=1, cbar=True, ax=None )` to solve the following problem:
Presents a `seaborn` heatmap visualization of nullity correlation in the given DataFrame. Note that this visualization has no special support for large datasets. For those, try the dendrogram instead. :param df: The DataFrame whose completeness is being heatmapped. :param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). See `nullity_filter()` for more information. :param n: The cap on the number of columns to include in the filtered DataFrame. See `nullity_filter()` for more information. :param p: The cap on the percentage fill of the columns in the filtered DataFrame. See `nullity_filter()` for more information. :param sort: The column sort order to apply. Can be "ascending", "descending", or None. :param figsize: The size of the figure to display. This is a `matplotlib` parameter which defaults to (20, 12). :param fontsize: The figure's font size. :param labels: Whether or not to label each matrix entry with its correlation (default is True). :param label_rotation: What angle to rotate the text labels to. Defaults to 45 degrees. :param cmap: What `matplotlib` colormap to use. Defaults to `RdBu`. :param vmin: The normalized colormap threshold. Defaults to -1, e.g. the bottom of the color scale. :param vmax: The normalized colormap threshold. Defaults to 1, e.g. the bottom of the color scale. :return: The plot axis.
Here is the function:
def heatmap(
df, filter=None, n=0, p=0, sort=None, figsize=(20, 12), fontsize=16, labels=True,
label_rotation=45, cmap='RdBu', vmin=-1, vmax=1, cbar=True, ax=None
):
"""
Presents a `seaborn` heatmap visualization of nullity correlation in the given DataFrame.
Note that this visualization has no special support for large datasets. For those, try the dendrogram instead.
:param df: The DataFrame whose completeness is being heatmapped.
:param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). See
`nullity_filter()` for more information.
:param n: The cap on the number of columns to include in the filtered DataFrame. See `nullity_filter()` for
more information.
:param p: The cap on the percentage fill of the columns in the filtered DataFrame. See `nullity_filter()` for
more information.
:param sort: The column sort order to apply. Can be "ascending", "descending", or None.
:param figsize: The size of the figure to display. This is a `matplotlib` parameter which defaults to (20, 12).
:param fontsize: The figure's font size.
:param labels: Whether or not to label each matrix entry with its correlation (default is True).
:param label_rotation: What angle to rotate the text labels to. Defaults to 45 degrees.
:param cmap: What `matplotlib` colormap to use. Defaults to `RdBu`.
:param vmin: The normalized colormap threshold. Defaults to -1, e.g. the bottom of the color scale.
:param vmax: The normalized colormap threshold. Defaults to 1, e.g. the bottom of the color scale.
:return: The plot axis.
"""
# Apply filters and sorts, set up the figure.
df = nullity_filter(df, filter=filter, n=n, p=p)
df = nullity_sort(df, sort=sort, axis='rows')
if ax is None:
plt.figure(figsize=figsize)
ax0 = plt.gca()
else:
ax0 = ax
# Remove completely filled or completely empty variables.
df = df.iloc[:, [i for i, n in enumerate(np.var(df.isnull(), axis='rows')) if n > 0]]
# Create and mask the correlation matrix. Construct the base heatmap.
corr_mat = df.isnull().corr()
mask = np.zeros_like(corr_mat)
mask[np.triu_indices_from(mask)] = True
if labels:
sns.heatmap(corr_mat, mask=mask, cmap=cmap, ax=ax0, cbar=cbar,
annot=True, annot_kws={'size': fontsize - 2},
vmin=vmin, vmax=vmax)
else:
sns.heatmap(corr_mat, mask=mask, cmap=cmap, ax=ax0, cbar=cbar,
vmin=vmin, vmax=vmax)
# Apply visual corrections and modifications.
ax0.xaxis.tick_bottom()
ax0.set_xticklabels(
ax0.xaxis.get_majorticklabels(), rotation=label_rotation, ha='right', fontsize=fontsize
)
ax0.set_yticklabels(ax0.yaxis.get_majorticklabels(), rotation=0, fontsize=fontsize)
ax0.xaxis.set_ticks_position('none')
ax0.yaxis.set_ticks_position('none')
ax0.patch.set_visible(False)
for text in ax0.texts:
t = float(text.get_text())
if 0.95 <= t < 1:
text.set_text('<1')
elif -1 < t <= -0.95:
text.set_text('>-1')
elif t == 1:
text.set_text('1')
elif t == -1:
text.set_text('-1')
elif -0.05 < t < 0.05:
text.set_text('')
else:
text.set_text(round(t, 1))
return ax0 | Presents a `seaborn` heatmap visualization of nullity correlation in the given DataFrame. Note that this visualization has no special support for large datasets. For those, try the dendrogram instead. :param df: The DataFrame whose completeness is being heatmapped. :param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). See `nullity_filter()` for more information. :param n: The cap on the number of columns to include in the filtered DataFrame. See `nullity_filter()` for more information. :param p: The cap on the percentage fill of the columns in the filtered DataFrame. See `nullity_filter()` for more information. :param sort: The column sort order to apply. Can be "ascending", "descending", or None. :param figsize: The size of the figure to display. This is a `matplotlib` parameter which defaults to (20, 12). :param fontsize: The figure's font size. :param labels: Whether or not to label each matrix entry with its correlation (default is True). :param label_rotation: What angle to rotate the text labels to. Defaults to 45 degrees. :param cmap: What `matplotlib` colormap to use. Defaults to `RdBu`. :param vmin: The normalized colormap threshold. Defaults to -1, e.g. the bottom of the color scale. :param vmax: The normalized colormap threshold. Defaults to 1, e.g. the bottom of the color scale. :return: The plot axis. |
158,316 | import numpy as np
import matplotlib as mpl
from matplotlib import gridspec
import matplotlib.pyplot as plt
from scipy.cluster import hierarchy
import seaborn as sns
import pandas as pd
from .utils import nullity_filter, nullity_sort
import warnings
def nullity_filter(df, filter=None, p=0, n=0):
"""
Filters a DataFrame according to its nullity, using some combination of 'top' and 'bottom' numerical and
percentage values. Percentages and numerical thresholds can be specified simultaneously: for example,
to get a DataFrame with columns of at least 75% completeness but with no more than 5 columns, use
`nullity_filter(df, filter='top', p=.75, n=5)`.
:param df: The DataFrame whose columns are being filtered.
:param filter: The orientation of the filter being applied to the DataFrame. One of, "top", "bottom",
or None (default). The filter will simply return the DataFrame if you leave the filter argument unspecified or
as None.
:param p: A completeness ratio cut-off. If non-zero the filter will limit the DataFrame to columns with at least p
completeness. Input should be in the range [0, 1].
:param n: A numerical cut-off. If non-zero no more than this number of columns will be returned.
:return: The nullity-filtered `DataFrame`.
"""
if filter == 'top':
if p:
df = df.iloc[:, [c >= p for c in df.count(axis='rows').values / len(df)]]
if n:
df = df.iloc[:, np.sort(np.argsort(df.count(axis='rows').values)[-n:])]
elif filter == 'bottom':
if p:
df = df.iloc[:, [c <= p for c in df.count(axis='rows').values / len(df)]]
if n:
df = df.iloc[:, np.sort(np.argsort(df.count(axis='rows').values)[:n])]
return df
The provided code snippet includes necessary dependencies for implementing the `dendrogram` function. Write a Python function `def dendrogram( df, method='average', filter=None, n=0, p=0, orientation=None, figsize=None, fontsize=16, label_rotation=45, ax=None )` to solve the following problem:
Fits a `scipy` hierarchical clustering algorithm to the given DataFrame's variables and visualizes the results as a `scipy` dendrogram. The default vertical display will fit up to 50 columns. If more than 50 columns are specified and orientation is left unspecified the dendrogram will automatically swap to a horizontal display to fit the additional variables. :param df: The DataFrame whose completeness is being dendrogrammed. :param method: The distance measure being used for clustering. This is a parameter that is passed to `scipy.hierarchy`. :param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). :param n: The cap on the number of columns to include in the filtered DataFrame. :param p: The cap on the percentage fill of the columns in the filtered DataFrame. :param figsize: The size of the figure to display. This is a `matplotlib` parameter which defaults to `(25, 10)`. :param fontsize: The figure's font size. :param orientation: The way the dendrogram is oriented. Defaults to top-down if there are less than or equal to 50 columns and left-right if there are more. :param label_rotation: What angle to rotate the text labels to. Defaults to 45 degrees. :return: The plot axis.
Here is the function:
def dendrogram(
df, method='average', filter=None, n=0, p=0, orientation=None, figsize=None, fontsize=16,
label_rotation=45, ax=None
):
"""
Fits a `scipy` hierarchical clustering algorithm to the given DataFrame's variables and visualizes the results as
a `scipy` dendrogram.
The default vertical display will fit up to 50 columns. If more than 50 columns are specified and orientation is
left unspecified the dendrogram will automatically swap to a horizontal display to fit the additional variables.
:param df: The DataFrame whose completeness is being dendrogrammed.
:param method: The distance measure being used for clustering. This is a parameter that is passed to
`scipy.hierarchy`.
:param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default).
:param n: The cap on the number of columns to include in the filtered DataFrame.
:param p: The cap on the percentage fill of the columns in the filtered DataFrame.
:param figsize: The size of the figure to display. This is a `matplotlib` parameter which defaults to `(25, 10)`.
:param fontsize: The figure's font size.
:param orientation: The way the dendrogram is oriented. Defaults to top-down if there are less than or equal to 50
columns and left-right if there are more.
:param label_rotation: What angle to rotate the text labels to. Defaults to 45 degrees.
:return: The plot axis.
"""
if not figsize:
if len(df.columns) <= 50 or orientation == 'top' or orientation == 'bottom':
figsize = (25, 10)
else:
figsize = (25, (25 + len(df.columns) - 50) * 0.5)
if ax is None:
plt.figure(figsize=figsize)
ax0 = plt.gca()
else:
ax0 = ax
df = nullity_filter(df, filter=filter, n=n, p=p)
# Link the hierarchical output matrix, figure out orientation, construct base dendrogram.
x = np.transpose(df.isnull().astype(int).values)
z = hierarchy.linkage(x, method)
if not orientation:
if len(df.columns) > 50:
orientation = 'left'
else:
orientation = 'bottom'
hierarchy.dendrogram(
z,
orientation=orientation,
labels=df.columns.tolist(),
distance_sort='descending',
link_color_func=lambda c: 'black',
leaf_font_size=fontsize,
ax=ax0
)
# Remove extraneous default visual elements.
ax0.set_aspect('auto')
ax0.grid(b=False)
if orientation == 'bottom':
ax0.xaxis.tick_top()
ax0.xaxis.set_ticks_position('none')
ax0.yaxis.set_ticks_position('none')
ax0.spines['top'].set_visible(False)
ax0.spines['right'].set_visible(False)
ax0.spines['bottom'].set_visible(False)
ax0.spines['left'].set_visible(False)
ax0.patch.set_visible(False)
# Set up the categorical axis labels and draw.
if orientation == 'bottom':
ax0.set_xticklabels(ax0.xaxis.get_majorticklabels(), rotation=label_rotation, ha='left')
elif orientation == 'top':
ax0.set_xticklabels(ax0.xaxis.get_majorticklabels(), rotation=label_rotation, ha='right')
if orientation == 'bottom' or orientation == 'top':
ax0.tick_params(axis='y', labelsize=int(fontsize / 16 * 20))
else:
ax0.tick_params(axis='x', labelsize=int(fontsize / 16 * 20))
return ax0 | Fits a `scipy` hierarchical clustering algorithm to the given DataFrame's variables and visualizes the results as a `scipy` dendrogram. The default vertical display will fit up to 50 columns. If more than 50 columns are specified and orientation is left unspecified the dendrogram will automatically swap to a horizontal display to fit the additional variables. :param df: The DataFrame whose completeness is being dendrogrammed. :param method: The distance measure being used for clustering. This is a parameter that is passed to `scipy.hierarchy`. :param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). :param n: The cap on the number of columns to include in the filtered DataFrame. :param p: The cap on the percentage fill of the columns in the filtered DataFrame. :param figsize: The size of the figure to display. This is a `matplotlib` parameter which defaults to `(25, 10)`. :param fontsize: The figure's font size. :param orientation: The way the dendrogram is oriented. Defaults to top-down if there are less than or equal to 50 columns and left-right if there are more. :param label_rotation: What angle to rotate the text labels to. Defaults to 45 degrees. :return: The plot axis. |
158,317 | from typing import Container, Dict, Type
from pydantic import BaseModel, create_model
from sqlalchemy.inspection import inspect
from sqlalchemy.orm.properties import ColumnProperty
The provided code snippet includes necessary dependencies for implementing the `sqlalchemy_to_pydantic` function. Write a Python function `def sqlalchemy_to_pydantic( db_model: Type, *, include: Dict[str, type] = None, exclude: Container[str] = None ) -> Type[BaseModel]` to solve the following problem:
Mostly copied from https://github.com/tiangolo/pydantic-sqlalchemy
Here is the function:
def sqlalchemy_to_pydantic(
db_model: Type, *, include: Dict[str, type] = None, exclude: Container[str] = None
) -> Type[BaseModel]:
"""
Mostly copied from https://github.com/tiangolo/pydantic-sqlalchemy
"""
if exclude is None:
exclude = []
mapper = inspect(db_model)
fields = {}
for attr in mapper.attrs:
if isinstance(attr, ColumnProperty):
if attr.columns:
column = attr.columns[0]
python_type = column.type.python_type
name = attr.key
if name in exclude:
continue
default = None
if column.default is None and not column.nullable:
default = ...
fields[name] = (python_type, default)
if bool(include):
for name, python_type in include.items():
default = None
fields[name] = (python_type, default)
pydantic_model = create_model(
db_model.__name__, **fields # type: ignore
)
return pydantic_model | Mostly copied from https://github.com/tiangolo/pydantic-sqlalchemy |
158,318 | from CTFd.utils.helpers.models import build_model_filters as _build_model_filters
def build_model_filters(model, query, field):
print("CTFd.api.v1.helpers.models.build_model_filters has been deprecated.")
print("Please switch to using CTFd.utils.helpers.models.build_model_filters")
print(
"This function will raise an exception in a future minor release of CTFd and then be removed in a major release."
)
return _build_model_filters(model, query, field) | null |
158,319 | from functools import wraps
from flask import request
from pydantic import ValidationError, create_model
ARG_LOCATIONS = {
"query": lambda: request.args,
"json": lambda: request.get_json(),
"form": lambda: request.form,
"headers": lambda: request.headers,
"cookies": lambda: request.cookies,
}
The provided code snippet includes necessary dependencies for implementing the `validate_args` function. Write a Python function `def validate_args(spec, location)` to solve the following problem:
A rough implementation of webargs using pydantic schemas. You can pass a pydantic schema as spec or create it on the fly as follows: @validate_args({"name": (str, None), "id": (int, None)}, location="query")
Here is the function:
def validate_args(spec, location):
"""
A rough implementation of webargs using pydantic schemas. You can pass a
pydantic schema as spec or create it on the fly as follows:
@validate_args({"name": (str, None), "id": (int, None)}, location="query")
"""
if isinstance(spec, dict):
spec = create_model("", **spec)
schema = spec.schema()
props = schema.get("properties", {})
required = schema.get("required", [])
for k in props:
if k in required:
props[k]["required"] = True
props[k]["in"] = location
def decorator(func):
# Inject parameters information into the Flask-Restx apidoc attribute.
# Not really a good solution. See https://github.com/CTFd/CTFd/issues/1504
apidoc = getattr(func, "__apidoc__", {"params": {}})
apidoc["params"].update(props)
func.__apidoc__ = apidoc
@wraps(func)
def wrapper(*args, **kwargs):
data = ARG_LOCATIONS[location]()
try:
# Try to load data according to pydantic spec
loaded = spec(**data).dict(exclude_unset=True)
except ValidationError as e:
# Handle reporting errors when invalid
resp = {}
errors = e.errors()
for err in errors:
loc = err["loc"][0]
msg = err["msg"]
resp[loc] = msg
return {"success": False, "errors": resp}, 400
return func(*args, loaded, **kwargs)
return wrapper
return decorator | A rough implementation of webargs using pydantic schemas. You can pass a pydantic schema as spec or create it on the fly as follows: @validate_args({"name": (str, None), "id": (int, None)}, location="query") |
158,320 | import datetime
from typing import List
from flask import abort, render_template, request, url_for
from flask_restx import Namespace, Resource
from sqlalchemy import func as sa_func
from sqlalchemy.sql import and_, false, true
from CTFd.api.v1.helpers.request import validate_args
from CTFd.api.v1.helpers.schemas import sqlalchemy_to_pydantic
from CTFd.api.v1.schemas import APIDetailedSuccessResponse, APIListSuccessResponse
from CTFd.cache import clear_standings
from CTFd.constants import RawEnum
from CTFd.models import ChallengeFiles as ChallengeFilesModel
from CTFd.models import (
Challenges,
Fails,
Flags,
Hints,
HintUnlocks,
Solves,
Submissions,
Tags,
db,
)
from CTFd.plugins.challenges import CHALLENGE_CLASSES, get_chal_class
from CTFd.schemas.challenges import ChallengeSchema
from CTFd.schemas.flags import FlagSchema
from CTFd.schemas.hints import HintSchema
from CTFd.schemas.tags import TagSchema
from CTFd.utils import config, get_config
from CTFd.utils import user as current_user
from CTFd.utils.config.visibility import (
accounts_visible,
challenges_visible,
scores_visible,
)
from CTFd.utils.dates import ctf_ended, ctf_paused, ctftime, isoformat, unix_time_to_utc
from CTFd.utils.decorators import (
admins_only,
during_ctf_time_only,
require_verified_emails,
)
from CTFd.utils.decorators.visibility import (
check_challenge_visibility,
check_score_visibility,
)
from CTFd.utils.helpers.models import build_model_filters
from CTFd.utils.logging import log
from CTFd.utils.modes import generate_account_url, get_model
from CTFd.utils.security.signing import serialize
from CTFd.utils.user import (
authed,
get_current_team,
get_current_team_attrs,
get_current_user,
get_current_user_attrs,
is_admin,
)
db = SQLAlchemy()
class Challenges(db.Model):
__tablename__ = "challenges"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80))
description = db.Column(db.Text)
max_attempts = db.Column(db.Integer, default=0)
value = db.Column(db.Integer)
category = db.Column(db.String(80))
type = db.Column(db.String(80))
state = db.Column(db.String(80), nullable=False, default="visible")
requirements = db.Column(db.JSON)
files = db.relationship("ChallengeFiles", backref="challenge")
tags = db.relationship("Tags", backref="challenge")
hints = db.relationship("Hints", backref="challenge")
flags = db.relationship("Flags", backref="challenge")
comments = db.relationship("ChallengeComments", backref="challenge")
class alt_defaultdict(defaultdict):
"""
This slightly modified defaultdict is intended to allow SQLAlchemy to
not fail when querying Challenges that contain a missing challenge type.
e.g. Challenges.query.all() should not fail if `type` is `a_missing_type`
"""
def __missing__(self, key):
return self["standard"]
__mapper_args__ = {
"polymorphic_identity": "standard",
"polymorphic_on": type,
"_polymorphic_map": alt_defaultdict(),
}
def html(self):
from CTFd.utils.config.pages import build_markdown
from CTFd.utils.helpers import markup
return markup(build_markdown(self.description))
def plugin_class(self):
from CTFd.plugins.challenges import get_chal_class
return get_chal_class(self.type)
def __init__(self, *args, **kwargs):
super(Challenges, self).__init__(**kwargs)
def __repr__(self):
return "<Challenge %r>" % self.name
class Solves(Submissions):
__tablename__ = "solves"
__table_args__ = (
db.UniqueConstraint("challenge_id", "user_id"),
db.UniqueConstraint("challenge_id", "team_id"),
{},
)
id = db.Column(
None, db.ForeignKey("submissions.id", ondelete="CASCADE"), primary_key=True
)
challenge_id = column_property(
db.Column(db.Integer, db.ForeignKey("challenges.id", ondelete="CASCADE")),
Submissions.challenge_id,
)
user_id = column_property(
db.Column(db.Integer, db.ForeignKey("users.id", ondelete="CASCADE")),
Submissions.user_id,
)
team_id = column_property(
db.Column(db.Integer, db.ForeignKey("teams.id", ondelete="CASCADE")),
Submissions.team_id,
)
user = db.relationship("Users", foreign_keys="Solves.user_id", lazy="select")
team = db.relationship("Teams", foreign_keys="Solves.team_id", lazy="select")
challenge = db.relationship(
"Challenges", foreign_keys="Solves.challenge_id", lazy="select"
)
__mapper_args__ = {"polymorphic_identity": "correct"}
def get_config(key, default=None):
# Convert enums to raw string values to cache better
if isinstance(key, Enum):
key = str(key)
value = _get_config(key)
if value is KeyError:
return default
else:
return value
def unix_time_to_utc(t):
return datetime.datetime.utcfromtimestamp(t)
def get_model():
if get_config("user_mode") == USERS_MODE:
return Users
elif get_config("user_mode") == TEAMS_MODE:
return Teams
def get_current_user():
if authed():
user = Users.query.filter_by(id=session["id"]).first()
# Check if the session is still valid
session_hash = session.get("hash")
if session_hash:
if session_hash != hmac(user.password):
logout_user()
if request.content_type == "application/json":
error = 401
else:
error = redirect(url_for("auth.login", next=request.full_path))
abort(error)
return user
else:
return None
The provided code snippet includes necessary dependencies for implementing the `_build_solves_query` function. Write a Python function `def _build_solves_query(extra_filters=(), admin_view=False)` to solve the following problem:
Returns queries and data that that are used for showing an account's solves. It returns a tuple of - SQLAlchemy query with (challenge_id, solve_count_for_challenge_id) - Current user's solved challenge IDs
Here is the function:
def _build_solves_query(extra_filters=(), admin_view=False):
"""Returns queries and data that that are used for showing an account's solves.
It returns a tuple of
- SQLAlchemy query with (challenge_id, solve_count_for_challenge_id)
- Current user's solved challenge IDs
"""
# This can return None (unauth) if visibility is set to public
user = get_current_user()
# We only set a condition for matching user solves if there is a user and
# they have an account ID (user mode or in a team in teams mode)
AccountModel = get_model()
if user is not None and user.account_id is not None:
user_solved_cond = Solves.account_id == user.account_id
else:
user_solved_cond = false()
# We have to filter solves to exclude any made after the current freeze
# time unless we're in an admin view as determined by the caller.
freeze = get_config("freeze")
if freeze and not admin_view:
freeze_cond = Solves.date < unix_time_to_utc(freeze)
else:
freeze_cond = true()
# Finally, we never count solves made by hidden or banned users/teams, even
# if we are an admin. This is to match the challenge detail API.
exclude_solves_cond = and_(
AccountModel.banned == false(), AccountModel.hidden == false(),
)
# This query counts the number of solves per challenge, as well as the sum
# of correct solves made by the current user per the condition above (which
# should probably only be 0 or 1!)
solves_q = (
db.session.query(Solves.challenge_id, sa_func.count(Solves.challenge_id),)
.join(AccountModel)
.filter(*extra_filters, freeze_cond, exclude_solves_cond)
.group_by(Solves.challenge_id)
)
# Also gather the user's solve items which can be different from above query
# For example, even if we are a hidden user, we should see that we have solved a challenge
# however as a hidden user we are not included in the count of the above query
if admin_view:
# If we're an admin we should show all challenges as solved to break through any requirements
challenges = Challenges.query.all()
solve_ids = {challenge.id for challenge in challenges}
else:
# If not an admin we calculate solves as normal
solve_ids = (
Solves.query.with_entities(Solves.challenge_id)
.filter(user_solved_cond)
.all()
)
solve_ids = {value for value, in solve_ids}
return solves_q, solve_ids | Returns queries and data that that are used for showing an account's solves. It returns a tuple of - SQLAlchemy query with (challenge_id, solve_count_for_challenge_id) - Current user's solved challenge IDs |
158,321 | from typing import List
from flask import request, session
from flask_restx import Namespace, Resource
from CTFd.api.v1.helpers.request import validate_args
from CTFd.api.v1.helpers.schemas import sqlalchemy_to_pydantic
from CTFd.api.v1.schemas import APIDetailedSuccessResponse, APIListSuccessResponse
from CTFd.constants import RawEnum
from CTFd.models import (
ChallengeComments,
Comments,
PageComments,
TeamComments,
UserComments,
db,
)
from CTFd.schemas.comments import CommentSchema
from CTFd.utils.decorators import admins_only
from CTFd.utils.helpers.models import build_model_filters
class Comments(db.Model):
def html(self):
class ChallengeComments(Comments):
class UserComments(Comments):
class TeamComments(Comments):
class PageComments(Comments):
def get_comment_model(data):
model = Comments
if "challenge_id" in data:
model = ChallengeComments
elif "user_id" in data:
model = UserComments
elif "team_id" in data:
model = TeamComments
elif "page_id" in data:
model = PageComments
else:
model = Comments
return model | null |
158,322 | import jinja2.exceptions
from flask import render_template
from werkzeug.exceptions import InternalServerError
def render_error(error):
if (
isinstance(error, InternalServerError)
and error.description == InternalServerError.description
):
error.description = "An Internal Server Error has occurred"
try:
return (
render_template(
"errors/{}.html".format(error.code), error=error.description,
),
error.code,
)
except jinja2.exceptions.TemplateNotFound:
return error.get_response() | null |
158,323 | from flask import Blueprint, abort, redirect, render_template, request, url_for
from CTFd.cache import clear_team_session, clear_user_session
from CTFd.exceptions import TeamTokenExpiredException, TeamTokenInvalidException
from CTFd.models import TeamFieldEntries, TeamFields, Teams, db
from CTFd.utils import config, get_config, validators
from CTFd.utils.crypto import verify_password
from CTFd.utils.decorators import authed_only, ratelimit, registered_only
from CTFd.utils.decorators.modes import require_team_mode
from CTFd.utils.decorators.visibility import (
check_account_visibility,
check_score_visibility,
)
from CTFd.utils.helpers import get_errors, get_infos
from CTFd.utils.humanize.words import pluralize
from CTFd.utils.user import get_current_user, get_current_user_attrs
teams = Blueprint("teams", __name__)
class Teams(db.Model):
__tablename__ = "teams"
__table_args__ = (db.UniqueConstraint("id", "oauth_id"), {})
# Core attributes
id = db.Column(db.Integer, primary_key=True)
oauth_id = db.Column(db.Integer, unique=True)
# Team names are not constrained to be unique to allow for official/unofficial teams.
name = db.Column(db.String(128))
email = db.Column(db.String(128), unique=True)
password = db.Column(db.String(128))
secret = db.Column(db.String(128))
members = db.relationship(
"Users", backref="team", foreign_keys="Users.team_id", lazy="joined"
)
# Supplementary attributes
website = db.Column(db.String(128))
affiliation = db.Column(db.String(128))
country = db.Column(db.String(32))
bracket = db.Column(db.String(32))
hidden = db.Column(db.Boolean, default=False)
banned = db.Column(db.Boolean, default=False)
# Relationship for Users
captain_id = db.Column(db.Integer, db.ForeignKey("users.id", ondelete="SET NULL"))
captain = db.relationship("Users", foreign_keys=[captain_id])
field_entries = db.relationship(
"TeamFieldEntries", foreign_keys="TeamFieldEntries.team_id", lazy="joined"
)
created = db.Column(db.DateTime, default=datetime.datetime.utcnow)
def __init__(self, **kwargs):
super(Teams, self).__init__(**kwargs)
def validate_password(self, key, plaintext):
from CTFd.utils.crypto import hash_password
return hash_password(str(plaintext))
def fields(self):
return self.get_fields(admin=False)
def solves(self):
return self.get_solves(admin=False)
def fails(self):
return self.get_fails(admin=False)
def awards(self):
return self.get_awards(admin=False)
def score(self):
return self.get_score(admin=False)
def place(self):
from CTFd.utils.config.visibility import scores_visible
if scores_visible():
return self.get_place(admin=False)
else:
return None
def get_fields(self, admin=False):
if admin:
return self.field_entries
return [
entry for entry in self.field_entries if entry.field.public and entry.value
]
def get_invite_code(self):
from flask import current_app
from CTFd.utils.security.signing import serialize, hmac
secret_key = current_app.config["SECRET_KEY"]
if isinstance(secret_key, str):
secret_key = secret_key.encode("utf-8")
team_password_key = self.password.encode("utf-8")
verification_secret = secret_key + team_password_key
invite_object = {
"id": self.id,
"v": hmac(str(self.id), secret=verification_secret),
}
code = serialize(data=invite_object, secret=secret_key)
return code
def load_invite_code(cls, code):
from flask import current_app
from CTFd.utils.security.signing import (
unserialize,
hmac,
BadTimeSignature,
BadSignature,
)
from CTFd.exceptions import TeamTokenExpiredException, TeamTokenInvalidException
secret_key = current_app.config["SECRET_KEY"]
if isinstance(secret_key, str):
secret_key = secret_key.encode("utf-8")
# Unserialize the invite code
try:
# Links expire after 1 day
invite_object = unserialize(code, max_age=86400)
except BadTimeSignature:
raise TeamTokenExpiredException
except BadSignature:
raise TeamTokenInvalidException
# Load the team by the ID in the invite
team_id = invite_object["id"]
team = cls.query.filter_by(id=team_id).first_or_404()
# Create the team specific secret
team_password_key = team.password.encode("utf-8")
verification_secret = secret_key + team_password_key
# Verify the team verficiation code
verified = hmac(str(team.id), secret=verification_secret) == invite_object["v"]
if verified is False:
raise TeamTokenInvalidException
return team
def get_solves(self, admin=False):
from CTFd.utils import get_config
member_ids = [member.id for member in self.members]
solves = Solves.query.filter(Solves.user_id.in_(member_ids)).order_by(
Solves.date.asc()
)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
solves = solves.filter(Solves.date < dt)
return solves.all()
def get_fails(self, admin=False):
from CTFd.utils import get_config
member_ids = [member.id for member in self.members]
fails = Fails.query.filter(Fails.user_id.in_(member_ids)).order_by(
Fails.date.asc()
)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
fails = fails.filter(Fails.date < dt)
return fails.all()
def get_awards(self, admin=False):
from CTFd.utils import get_config
member_ids = [member.id for member in self.members]
awards = Awards.query.filter(Awards.user_id.in_(member_ids)).order_by(
Awards.date.asc()
)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
awards = awards.filter(Awards.date < dt)
return awards.all()
def get_score(self, admin=False):
score = 0
for member in self.members:
score += member.get_score(admin=admin)
return score
def get_place(self, admin=False, numeric=False):
"""
This method is generally a clone of CTFd.scoreboard.get_standings.
The point being that models.py must be self-reliant and have little
to no imports within the CTFd application as importing from the
application itself will result in a circular import.
"""
from CTFd.utils.scores import get_team_standings
from CTFd.utils.humanize.numbers import ordinalize
standings = get_team_standings(admin=admin)
for i, team in enumerate(standings):
if team.team_id == self.id:
n = i + 1
if numeric:
return n
return ordinalize(n)
else:
return None
def listing():
q = request.args.get("q")
field = request.args.get("field", "name")
filters = []
if field not in ("name", "affiliation", "website"):
field = "name"
if q:
filters.append(getattr(Teams, field).like("%{}%".format(q)))
teams = (
Teams.query.filter_by(hidden=False, banned=False)
.filter(*filters)
.order_by(Teams.id.asc())
.paginate(per_page=50)
)
args = dict(request.args)
args.pop("page", 1)
return render_template(
"teams/teams.html",
teams=teams,
prev_page=url_for(request.endpoint, page=teams.prev_num, **args),
next_page=url_for(request.endpoint, page=teams.next_num, **args),
q=q,
field=field,
) | null |
158,324 | from flask import Blueprint, abort, redirect, render_template, request, url_for
from CTFd.cache import clear_team_session, clear_user_session
from CTFd.exceptions import TeamTokenExpiredException, TeamTokenInvalidException
from CTFd.models import TeamFieldEntries, TeamFields, Teams, db
from CTFd.utils import config, get_config, validators
from CTFd.utils.crypto import verify_password
from CTFd.utils.decorators import authed_only, ratelimit, registered_only
from CTFd.utils.decorators.modes import require_team_mode
from CTFd.utils.decorators.visibility import (
check_account_visibility,
check_score_visibility,
)
from CTFd.utils.helpers import get_errors, get_infos
from CTFd.utils.humanize.words import pluralize
from CTFd.utils.user import get_current_user, get_current_user_attrs
def clear_user_session(user_id):
def clear_team_session(team_id):
class TeamTokenExpiredException(Exception):
class TeamTokenInvalidException(Exception):
db = SQLAlchemy()
class Teams(db.Model):
def __init__(self, **kwargs):
def validate_password(self, key, plaintext):
def fields(self):
def solves(self):
def fails(self):
def awards(self):
def score(self):
def place(self):
def get_fields(self, admin=False):
def get_invite_code(self):
def load_invite_code(cls, code):
def get_solves(self, admin=False):
def get_fails(self, admin=False):
def get_awards(self, admin=False):
def get_score(self, admin=False):
def get_place(self, admin=False, numeric=False):
def get_config(key, default=None):
def get_infos():
def get_errors():
def pluralize(number, singular="", plural="s"):
def get_current_user():
def get_current_user_attrs():
def invite():
infos = get_infos()
errors = get_errors()
code = request.args.get("code")
if code is None:
abort(404)
user = get_current_user_attrs()
if user.team_id:
errors.append("You are already in a team. You cannot join another.")
try:
team = Teams.load_invite_code(code)
except TeamTokenExpiredException:
abort(403, description="This invite URL has expired")
except TeamTokenInvalidException:
abort(403, description="This invite URL is invalid")
team_size_limit = get_config("team_size", default=0)
if request.method == "GET":
if team_size_limit:
infos.append(
"Teams are limited to {limit} member{plural}".format(
limit=team_size_limit, plural=pluralize(number=team_size_limit)
)
)
return render_template(
"teams/invite.html", team=team, infos=infos, errors=errors
)
if request.method == "POST":
if errors:
return (
render_template(
"teams/invite.html", team=team, infos=infos, errors=errors
),
403,
)
if team_size_limit and len(team.members) >= team_size_limit:
errors.append(
"{name} has already reached the team size limit of {limit}".format(
name=team.name, limit=team_size_limit
)
)
return (
render_template(
"teams/invite.html", team=team, infos=infos, errors=errors
),
403,
)
user = get_current_user()
user.team_id = team.id
db.session.commit()
clear_user_session(user_id=user.id)
clear_team_session(team_id=team.id)
return redirect(url_for("challenges.listing")) | null |
158,325 | from flask import Blueprint, abort, redirect, render_template, request, url_for
from CTFd.cache import clear_team_session, clear_user_session
from CTFd.exceptions import TeamTokenExpiredException, TeamTokenInvalidException
from CTFd.models import TeamFieldEntries, TeamFields, Teams, db
from CTFd.utils import config, get_config, validators
from CTFd.utils.crypto import verify_password
from CTFd.utils.decorators import authed_only, ratelimit, registered_only
from CTFd.utils.decorators.modes import require_team_mode
from CTFd.utils.decorators.visibility import (
check_account_visibility,
check_score_visibility,
)
from CTFd.utils.helpers import get_errors, get_infos
from CTFd.utils.humanize.words import pluralize
from CTFd.utils.user import get_current_user, get_current_user_attrs
def clear_user_session(user_id):
from CTFd.utils.user import get_user_attrs
cache.delete_memoized(get_user_attrs, user_id=user_id)
def clear_team_session(team_id):
from CTFd.utils.user import get_team_attrs
cache.delete_memoized(get_team_attrs, team_id=team_id)
db = SQLAlchemy()
class Teams(db.Model):
__tablename__ = "teams"
__table_args__ = (db.UniqueConstraint("id", "oauth_id"), {})
# Core attributes
id = db.Column(db.Integer, primary_key=True)
oauth_id = db.Column(db.Integer, unique=True)
# Team names are not constrained to be unique to allow for official/unofficial teams.
name = db.Column(db.String(128))
email = db.Column(db.String(128), unique=True)
password = db.Column(db.String(128))
secret = db.Column(db.String(128))
members = db.relationship(
"Users", backref="team", foreign_keys="Users.team_id", lazy="joined"
)
# Supplementary attributes
website = db.Column(db.String(128))
affiliation = db.Column(db.String(128))
country = db.Column(db.String(32))
bracket = db.Column(db.String(32))
hidden = db.Column(db.Boolean, default=False)
banned = db.Column(db.Boolean, default=False)
# Relationship for Users
captain_id = db.Column(db.Integer, db.ForeignKey("users.id", ondelete="SET NULL"))
captain = db.relationship("Users", foreign_keys=[captain_id])
field_entries = db.relationship(
"TeamFieldEntries", foreign_keys="TeamFieldEntries.team_id", lazy="joined"
)
created = db.Column(db.DateTime, default=datetime.datetime.utcnow)
def __init__(self, **kwargs):
super(Teams, self).__init__(**kwargs)
def validate_password(self, key, plaintext):
from CTFd.utils.crypto import hash_password
return hash_password(str(plaintext))
def fields(self):
return self.get_fields(admin=False)
def solves(self):
return self.get_solves(admin=False)
def fails(self):
return self.get_fails(admin=False)
def awards(self):
return self.get_awards(admin=False)
def score(self):
return self.get_score(admin=False)
def place(self):
from CTFd.utils.config.visibility import scores_visible
if scores_visible():
return self.get_place(admin=False)
else:
return None
def get_fields(self, admin=False):
if admin:
return self.field_entries
return [
entry for entry in self.field_entries if entry.field.public and entry.value
]
def get_invite_code(self):
from flask import current_app
from CTFd.utils.security.signing import serialize, hmac
secret_key = current_app.config["SECRET_KEY"]
if isinstance(secret_key, str):
secret_key = secret_key.encode("utf-8")
team_password_key = self.password.encode("utf-8")
verification_secret = secret_key + team_password_key
invite_object = {
"id": self.id,
"v": hmac(str(self.id), secret=verification_secret),
}
code = serialize(data=invite_object, secret=secret_key)
return code
def load_invite_code(cls, code):
from flask import current_app
from CTFd.utils.security.signing import (
unserialize,
hmac,
BadTimeSignature,
BadSignature,
)
from CTFd.exceptions import TeamTokenExpiredException, TeamTokenInvalidException
secret_key = current_app.config["SECRET_KEY"]
if isinstance(secret_key, str):
secret_key = secret_key.encode("utf-8")
# Unserialize the invite code
try:
# Links expire after 1 day
invite_object = unserialize(code, max_age=86400)
except BadTimeSignature:
raise TeamTokenExpiredException
except BadSignature:
raise TeamTokenInvalidException
# Load the team by the ID in the invite
team_id = invite_object["id"]
team = cls.query.filter_by(id=team_id).first_or_404()
# Create the team specific secret
team_password_key = team.password.encode("utf-8")
verification_secret = secret_key + team_password_key
# Verify the team verficiation code
verified = hmac(str(team.id), secret=verification_secret) == invite_object["v"]
if verified is False:
raise TeamTokenInvalidException
return team
def get_solves(self, admin=False):
from CTFd.utils import get_config
member_ids = [member.id for member in self.members]
solves = Solves.query.filter(Solves.user_id.in_(member_ids)).order_by(
Solves.date.asc()
)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
solves = solves.filter(Solves.date < dt)
return solves.all()
def get_fails(self, admin=False):
from CTFd.utils import get_config
member_ids = [member.id for member in self.members]
fails = Fails.query.filter(Fails.user_id.in_(member_ids)).order_by(
Fails.date.asc()
)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
fails = fails.filter(Fails.date < dt)
return fails.all()
def get_awards(self, admin=False):
from CTFd.utils import get_config
member_ids = [member.id for member in self.members]
awards = Awards.query.filter(Awards.user_id.in_(member_ids)).order_by(
Awards.date.asc()
)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
awards = awards.filter(Awards.date < dt)
return awards.all()
def get_score(self, admin=False):
score = 0
for member in self.members:
score += member.get_score(admin=admin)
return score
def get_place(self, admin=False, numeric=False):
"""
This method is generally a clone of CTFd.scoreboard.get_standings.
The point being that models.py must be self-reliant and have little
to no imports within the CTFd application as importing from the
application itself will result in a circular import.
"""
from CTFd.utils.scores import get_team_standings
from CTFd.utils.humanize.numbers import ordinalize
standings = get_team_standings(admin=admin)
for i, team in enumerate(standings):
if team.team_id == self.id:
n = i + 1
if numeric:
return n
return ordinalize(n)
else:
return None
def get_config(key, default=None):
# Convert enums to raw string values to cache better
if isinstance(key, Enum):
key = str(key)
value = _get_config(key)
if value is KeyError:
return default
else:
return value
def verify_password(plaintext, ciphertext):
return bcrypt_sha256.verify(plaintext, ciphertext)
def get_infos():
return get_flashed_messages(category_filter=request.endpoint + ".infos")
def get_errors():
return get_flashed_messages(category_filter=request.endpoint + ".errors")
def get_current_user():
if authed():
user = Users.query.filter_by(id=session["id"]).first()
# Check if the session is still valid
session_hash = session.get("hash")
if session_hash:
if session_hash != hmac(user.password):
logout_user()
if request.content_type == "application/json":
error = 401
else:
error = redirect(url_for("auth.login", next=request.full_path))
abort(error)
return user
else:
return None
def get_current_user_attrs():
if authed():
return get_user_attrs(user_id=session["id"])
else:
return None
def join():
infos = get_infos()
errors = get_errors()
user = get_current_user_attrs()
if user.team_id:
errors.append("You are already in a team. You cannot join another.")
if request.method == "GET":
team_size_limit = get_config("team_size", default=0)
if team_size_limit:
plural = "" if team_size_limit == 1 else "s"
infos.append(
"Teams are limited to {limit} member{plural}".format(
limit=team_size_limit, plural=plural
)
)
return render_template("teams/join_team.html", infos=infos, errors=errors)
if request.method == "POST":
teamname = request.form.get("name")
passphrase = request.form.get("password", "").strip()
team = Teams.query.filter_by(name=teamname).first()
if errors:
return (
render_template("teams/join_team.html", infos=infos, errors=errors),
403,
)
if team and verify_password(passphrase, team.password):
team_size_limit = get_config("team_size", default=0)
if team_size_limit and len(team.members) >= team_size_limit:
errors.append(
"{name} has already reached the team size limit of {limit}".format(
name=team.name, limit=team_size_limit
)
)
return render_template(
"teams/join_team.html", infos=infos, errors=errors
)
user = get_current_user()
user.team_id = team.id
db.session.commit()
if len(team.members) == 1:
team.captain_id = user.id
db.session.commit()
clear_user_session(user_id=user.id)
clear_team_session(team_id=team.id)
return redirect(url_for("challenges.listing"))
else:
errors.append("That information is incorrect")
return render_template("teams/join_team.html", infos=infos, errors=errors) | null |
158,326 | from flask import Blueprint, abort, redirect, render_template, request, url_for
from CTFd.cache import clear_team_session, clear_user_session
from CTFd.exceptions import TeamTokenExpiredException, TeamTokenInvalidException
from CTFd.models import TeamFieldEntries, TeamFields, Teams, db
from CTFd.utils import config, get_config, validators
from CTFd.utils.crypto import verify_password
from CTFd.utils.decorators import authed_only, ratelimit, registered_only
from CTFd.utils.decorators.modes import require_team_mode
from CTFd.utils.decorators.visibility import (
check_account_visibility,
check_score_visibility,
)
from CTFd.utils.helpers import get_errors, get_infos
from CTFd.utils.humanize.words import pluralize
from CTFd.utils.user import get_current_user, get_current_user_attrs
def clear_user_session(user_id):
from CTFd.utils.user import get_user_attrs
cache.delete_memoized(get_user_attrs, user_id=user_id)
def clear_team_session(team_id):
from CTFd.utils.user import get_team_attrs
cache.delete_memoized(get_team_attrs, team_id=team_id)
db = SQLAlchemy()
class Teams(db.Model):
__tablename__ = "teams"
__table_args__ = (db.UniqueConstraint("id", "oauth_id"), {})
# Core attributes
id = db.Column(db.Integer, primary_key=True)
oauth_id = db.Column(db.Integer, unique=True)
# Team names are not constrained to be unique to allow for official/unofficial teams.
name = db.Column(db.String(128))
email = db.Column(db.String(128), unique=True)
password = db.Column(db.String(128))
secret = db.Column(db.String(128))
members = db.relationship(
"Users", backref="team", foreign_keys="Users.team_id", lazy="joined"
)
# Supplementary attributes
website = db.Column(db.String(128))
affiliation = db.Column(db.String(128))
country = db.Column(db.String(32))
bracket = db.Column(db.String(32))
hidden = db.Column(db.Boolean, default=False)
banned = db.Column(db.Boolean, default=False)
# Relationship for Users
captain_id = db.Column(db.Integer, db.ForeignKey("users.id", ondelete="SET NULL"))
captain = db.relationship("Users", foreign_keys=[captain_id])
field_entries = db.relationship(
"TeamFieldEntries", foreign_keys="TeamFieldEntries.team_id", lazy="joined"
)
created = db.Column(db.DateTime, default=datetime.datetime.utcnow)
def __init__(self, **kwargs):
super(Teams, self).__init__(**kwargs)
def validate_password(self, key, plaintext):
from CTFd.utils.crypto import hash_password
return hash_password(str(plaintext))
def fields(self):
return self.get_fields(admin=False)
def solves(self):
return self.get_solves(admin=False)
def fails(self):
return self.get_fails(admin=False)
def awards(self):
return self.get_awards(admin=False)
def score(self):
return self.get_score(admin=False)
def place(self):
from CTFd.utils.config.visibility import scores_visible
if scores_visible():
return self.get_place(admin=False)
else:
return None
def get_fields(self, admin=False):
if admin:
return self.field_entries
return [
entry for entry in self.field_entries if entry.field.public and entry.value
]
def get_invite_code(self):
from flask import current_app
from CTFd.utils.security.signing import serialize, hmac
secret_key = current_app.config["SECRET_KEY"]
if isinstance(secret_key, str):
secret_key = secret_key.encode("utf-8")
team_password_key = self.password.encode("utf-8")
verification_secret = secret_key + team_password_key
invite_object = {
"id": self.id,
"v": hmac(str(self.id), secret=verification_secret),
}
code = serialize(data=invite_object, secret=secret_key)
return code
def load_invite_code(cls, code):
from flask import current_app
from CTFd.utils.security.signing import (
unserialize,
hmac,
BadTimeSignature,
BadSignature,
)
from CTFd.exceptions import TeamTokenExpiredException, TeamTokenInvalidException
secret_key = current_app.config["SECRET_KEY"]
if isinstance(secret_key, str):
secret_key = secret_key.encode("utf-8")
# Unserialize the invite code
try:
# Links expire after 1 day
invite_object = unserialize(code, max_age=86400)
except BadTimeSignature:
raise TeamTokenExpiredException
except BadSignature:
raise TeamTokenInvalidException
# Load the team by the ID in the invite
team_id = invite_object["id"]
team = cls.query.filter_by(id=team_id).first_or_404()
# Create the team specific secret
team_password_key = team.password.encode("utf-8")
verification_secret = secret_key + team_password_key
# Verify the team verficiation code
verified = hmac(str(team.id), secret=verification_secret) == invite_object["v"]
if verified is False:
raise TeamTokenInvalidException
return team
def get_solves(self, admin=False):
from CTFd.utils import get_config
member_ids = [member.id for member in self.members]
solves = Solves.query.filter(Solves.user_id.in_(member_ids)).order_by(
Solves.date.asc()
)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
solves = solves.filter(Solves.date < dt)
return solves.all()
def get_fails(self, admin=False):
from CTFd.utils import get_config
member_ids = [member.id for member in self.members]
fails = Fails.query.filter(Fails.user_id.in_(member_ids)).order_by(
Fails.date.asc()
)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
fails = fails.filter(Fails.date < dt)
return fails.all()
def get_awards(self, admin=False):
from CTFd.utils import get_config
member_ids = [member.id for member in self.members]
awards = Awards.query.filter(Awards.user_id.in_(member_ids)).order_by(
Awards.date.asc()
)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
awards = awards.filter(Awards.date < dt)
return awards.all()
def get_score(self, admin=False):
score = 0
for member in self.members:
score += member.get_score(admin=admin)
return score
def get_place(self, admin=False, numeric=False):
"""
This method is generally a clone of CTFd.scoreboard.get_standings.
The point being that models.py must be self-reliant and have little
to no imports within the CTFd application as importing from the
application itself will result in a circular import.
"""
from CTFd.utils.scores import get_team_standings
from CTFd.utils.humanize.numbers import ordinalize
standings = get_team_standings(admin=admin)
for i, team in enumerate(standings):
if team.team_id == self.id:
n = i + 1
if numeric:
return n
return ordinalize(n)
else:
return None
class TeamFields(Fields):
__mapper_args__ = {"polymorphic_identity": "team"}
class TeamFieldEntries(FieldEntries):
__mapper_args__ = {"polymorphic_identity": "team"}
team_id = db.Column(db.Integer, db.ForeignKey("teams.id", ondelete="CASCADE"))
team = db.relationship("Teams", foreign_keys="TeamFieldEntries.team_id")
def get_config(key, default=None):
# Convert enums to raw string values to cache better
if isinstance(key, Enum):
key = str(key)
value = _get_config(key)
if value is KeyError:
return default
else:
return value
def get_infos():
return get_flashed_messages(category_filter=request.endpoint + ".infos")
def get_errors():
return get_flashed_messages(category_filter=request.endpoint + ".errors")
def get_current_user():
if authed():
user = Users.query.filter_by(id=session["id"]).first()
# Check if the session is still valid
session_hash = session.get("hash")
if session_hash:
if session_hash != hmac(user.password):
logout_user()
if request.content_type == "application/json":
error = 401
else:
error = redirect(url_for("auth.login", next=request.full_path))
abort(error)
return user
else:
return None
def get_current_user_attrs():
if authed():
return get_user_attrs(user_id=session["id"])
else:
return None
def new():
infos = get_infos()
errors = get_errors()
if bool(get_config("team_creation", default=True)) is False:
abort(
403,
description="Team creation is currently disabled. Please join an existing team.",
)
num_teams_limit = int(get_config("num_teams", default=0))
num_teams = Teams.query.filter_by(banned=False, hidden=False).count()
if num_teams_limit and num_teams >= num_teams_limit:
abort(
403,
description=f"Reached the maximum number of teams ({num_teams_limit}). Please join an existing team.",
)
user = get_current_user_attrs()
if user.team_id:
errors.append("You are already in a team. You cannot join another.")
if request.method == "GET":
team_size_limit = get_config("team_size", default=0)
if team_size_limit:
plural = "" if team_size_limit == 1 else "s"
infos.append(
"Teams are limited to {limit} member{plural}".format(
limit=team_size_limit, plural=plural
)
)
return render_template("teams/new_team.html", infos=infos, errors=errors)
elif request.method == "POST":
teamname = request.form.get("name", "").strip()
passphrase = request.form.get("password", "").strip()
website = request.form.get("website")
affiliation = request.form.get("affiliation")
user = get_current_user()
existing_team = Teams.query.filter_by(name=teamname).first()
if existing_team:
errors.append("That team name is already taken")
if not teamname:
errors.append("That team name is invalid")
# Process additional user fields
fields = {}
for field in TeamFields.query.all():
fields[field.id] = field
entries = {}
for field_id, field in fields.items():
value = request.form.get(f"fields[{field_id}]", "").strip()
if field.required is True and (value is None or value == ""):
errors.append("Please provide all required fields")
break
# Handle special casing of existing profile fields
if field.name.lower() == "affiliation":
affiliation = value
break
elif field.name.lower() == "website":
website = value
break
if field.field_type == "boolean":
entries[field_id] = bool(value)
else:
entries[field_id] = value
if website:
valid_website = validators.validate_url(website)
else:
valid_website = True
if affiliation:
valid_affiliation = len(affiliation) < 128
else:
valid_affiliation = True
if valid_website is False:
errors.append("Websites must be a proper URL starting with http or https")
if valid_affiliation is False:
errors.append("Please provide a shorter affiliation")
if errors:
return render_template("teams/new_team.html", errors=errors), 403
team = Teams(name=teamname, password=passphrase, captain_id=user.id)
if website:
team.website = website
if affiliation:
team.affiliation = affiliation
db.session.add(team)
db.session.commit()
for field_id, value in entries.items():
entry = TeamFieldEntries(field_id=field_id, value=value, team_id=team.id)
db.session.add(entry)
db.session.commit()
user.team_id = team.id
db.session.commit()
clear_user_session(user_id=user.id)
clear_team_session(team_id=team.id)
return redirect(url_for("challenges.listing")) | null |
158,327 | from flask import Blueprint, abort, redirect, render_template, request, url_for
from CTFd.cache import clear_team_session, clear_user_session
from CTFd.exceptions import TeamTokenExpiredException, TeamTokenInvalidException
from CTFd.models import TeamFieldEntries, TeamFields, Teams, db
from CTFd.utils import config, get_config, validators
from CTFd.utils.crypto import verify_password
from CTFd.utils.decorators import authed_only, ratelimit, registered_only
from CTFd.utils.decorators.modes import require_team_mode
from CTFd.utils.decorators.visibility import (
check_account_visibility,
check_score_visibility,
)
from CTFd.utils.helpers import get_errors, get_infos
from CTFd.utils.humanize.words import pluralize
from CTFd.utils.user import get_current_user, get_current_user_attrs
class Teams(db.Model):
__tablename__ = "teams"
__table_args__ = (db.UniqueConstraint("id", "oauth_id"), {})
# Core attributes
id = db.Column(db.Integer, primary_key=True)
oauth_id = db.Column(db.Integer, unique=True)
# Team names are not constrained to be unique to allow for official/unofficial teams.
name = db.Column(db.String(128))
email = db.Column(db.String(128), unique=True)
password = db.Column(db.String(128))
secret = db.Column(db.String(128))
members = db.relationship(
"Users", backref="team", foreign_keys="Users.team_id", lazy="joined"
)
# Supplementary attributes
website = db.Column(db.String(128))
affiliation = db.Column(db.String(128))
country = db.Column(db.String(32))
bracket = db.Column(db.String(32))
hidden = db.Column(db.Boolean, default=False)
banned = db.Column(db.Boolean, default=False)
# Relationship for Users
captain_id = db.Column(db.Integer, db.ForeignKey("users.id", ondelete="SET NULL"))
captain = db.relationship("Users", foreign_keys=[captain_id])
field_entries = db.relationship(
"TeamFieldEntries", foreign_keys="TeamFieldEntries.team_id", lazy="joined"
)
created = db.Column(db.DateTime, default=datetime.datetime.utcnow)
def __init__(self, **kwargs):
super(Teams, self).__init__(**kwargs)
def validate_password(self, key, plaintext):
from CTFd.utils.crypto import hash_password
return hash_password(str(plaintext))
def fields(self):
return self.get_fields(admin=False)
def solves(self):
return self.get_solves(admin=False)
def fails(self):
return self.get_fails(admin=False)
def awards(self):
return self.get_awards(admin=False)
def score(self):
return self.get_score(admin=False)
def place(self):
from CTFd.utils.config.visibility import scores_visible
if scores_visible():
return self.get_place(admin=False)
else:
return None
def get_fields(self, admin=False):
if admin:
return self.field_entries
return [
entry for entry in self.field_entries if entry.field.public and entry.value
]
def get_invite_code(self):
from flask import current_app
from CTFd.utils.security.signing import serialize, hmac
secret_key = current_app.config["SECRET_KEY"]
if isinstance(secret_key, str):
secret_key = secret_key.encode("utf-8")
team_password_key = self.password.encode("utf-8")
verification_secret = secret_key + team_password_key
invite_object = {
"id": self.id,
"v": hmac(str(self.id), secret=verification_secret),
}
code = serialize(data=invite_object, secret=secret_key)
return code
def load_invite_code(cls, code):
from flask import current_app
from CTFd.utils.security.signing import (
unserialize,
hmac,
BadTimeSignature,
BadSignature,
)
from CTFd.exceptions import TeamTokenExpiredException, TeamTokenInvalidException
secret_key = current_app.config["SECRET_KEY"]
if isinstance(secret_key, str):
secret_key = secret_key.encode("utf-8")
# Unserialize the invite code
try:
# Links expire after 1 day
invite_object = unserialize(code, max_age=86400)
except BadTimeSignature:
raise TeamTokenExpiredException
except BadSignature:
raise TeamTokenInvalidException
# Load the team by the ID in the invite
team_id = invite_object["id"]
team = cls.query.filter_by(id=team_id).first_or_404()
# Create the team specific secret
team_password_key = team.password.encode("utf-8")
verification_secret = secret_key + team_password_key
# Verify the team verficiation code
verified = hmac(str(team.id), secret=verification_secret) == invite_object["v"]
if verified is False:
raise TeamTokenInvalidException
return team
def get_solves(self, admin=False):
from CTFd.utils import get_config
member_ids = [member.id for member in self.members]
solves = Solves.query.filter(Solves.user_id.in_(member_ids)).order_by(
Solves.date.asc()
)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
solves = solves.filter(Solves.date < dt)
return solves.all()
def get_fails(self, admin=False):
from CTFd.utils import get_config
member_ids = [member.id for member in self.members]
fails = Fails.query.filter(Fails.user_id.in_(member_ids)).order_by(
Fails.date.asc()
)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
fails = fails.filter(Fails.date < dt)
return fails.all()
def get_awards(self, admin=False):
from CTFd.utils import get_config
member_ids = [member.id for member in self.members]
awards = Awards.query.filter(Awards.user_id.in_(member_ids)).order_by(
Awards.date.asc()
)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
awards = awards.filter(Awards.date < dt)
return awards.all()
def get_score(self, admin=False):
score = 0
for member in self.members:
score += member.get_score(admin=admin)
return score
def get_place(self, admin=False, numeric=False):
"""
This method is generally a clone of CTFd.scoreboard.get_standings.
The point being that models.py must be self-reliant and have little
to no imports within the CTFd application as importing from the
application itself will result in a circular import.
"""
from CTFd.utils.scores import get_team_standings
from CTFd.utils.humanize.numbers import ordinalize
standings = get_team_standings(admin=admin)
for i, team in enumerate(standings):
if team.team_id == self.id:
n = i + 1
if numeric:
return n
return ordinalize(n)
else:
return None
def get_infos():
return get_flashed_messages(category_filter=request.endpoint + ".infos")
def get_errors():
return get_flashed_messages(category_filter=request.endpoint + ".errors")
def get_current_user():
if authed():
user = Users.query.filter_by(id=session["id"]).first()
# Check if the session is still valid
session_hash = session.get("hash")
if session_hash:
if session_hash != hmac(user.password):
logout_user()
if request.content_type == "application/json":
error = 401
else:
error = redirect(url_for("auth.login", next=request.full_path))
abort(error)
return user
else:
return None
def private():
infos = get_infos()
errors = get_errors()
user = get_current_user()
if not user.team_id:
return render_template("teams/team_enrollment.html")
team_id = user.team_id
team = Teams.query.filter_by(id=team_id).first_or_404()
solves = team.get_solves()
awards = team.get_awards()
place = team.place
score = team.score
if config.is_scoreboard_frozen():
infos.append("Scoreboard has been frozen")
return render_template(
"teams/private.html",
solves=solves,
awards=awards,
user=user,
team=team,
score=score,
place=place,
score_frozen=config.is_scoreboard_frozen(),
infos=infos,
errors=errors,
) | null |
158,328 | from flask import Blueprint, abort, redirect, render_template, request, url_for
from CTFd.cache import clear_team_session, clear_user_session
from CTFd.exceptions import TeamTokenExpiredException, TeamTokenInvalidException
from CTFd.models import TeamFieldEntries, TeamFields, Teams, db
from CTFd.utils import config, get_config, validators
from CTFd.utils.crypto import verify_password
from CTFd.utils.decorators import authed_only, ratelimit, registered_only
from CTFd.utils.decorators.modes import require_team_mode
from CTFd.utils.decorators.visibility import (
check_account_visibility,
check_score_visibility,
)
from CTFd.utils.helpers import get_errors, get_infos
from CTFd.utils.humanize.words import pluralize
from CTFd.utils.user import get_current_user, get_current_user_attrs
class Teams(db.Model):
__tablename__ = "teams"
__table_args__ = (db.UniqueConstraint("id", "oauth_id"), {})
# Core attributes
id = db.Column(db.Integer, primary_key=True)
oauth_id = db.Column(db.Integer, unique=True)
# Team names are not constrained to be unique to allow for official/unofficial teams.
name = db.Column(db.String(128))
email = db.Column(db.String(128), unique=True)
password = db.Column(db.String(128))
secret = db.Column(db.String(128))
members = db.relationship(
"Users", backref="team", foreign_keys="Users.team_id", lazy="joined"
)
# Supplementary attributes
website = db.Column(db.String(128))
affiliation = db.Column(db.String(128))
country = db.Column(db.String(32))
bracket = db.Column(db.String(32))
hidden = db.Column(db.Boolean, default=False)
banned = db.Column(db.Boolean, default=False)
# Relationship for Users
captain_id = db.Column(db.Integer, db.ForeignKey("users.id", ondelete="SET NULL"))
captain = db.relationship("Users", foreign_keys=[captain_id])
field_entries = db.relationship(
"TeamFieldEntries", foreign_keys="TeamFieldEntries.team_id", lazy="joined"
)
created = db.Column(db.DateTime, default=datetime.datetime.utcnow)
def __init__(self, **kwargs):
super(Teams, self).__init__(**kwargs)
def validate_password(self, key, plaintext):
from CTFd.utils.crypto import hash_password
return hash_password(str(plaintext))
def fields(self):
return self.get_fields(admin=False)
def solves(self):
return self.get_solves(admin=False)
def fails(self):
return self.get_fails(admin=False)
def awards(self):
return self.get_awards(admin=False)
def score(self):
return self.get_score(admin=False)
def place(self):
from CTFd.utils.config.visibility import scores_visible
if scores_visible():
return self.get_place(admin=False)
else:
return None
def get_fields(self, admin=False):
if admin:
return self.field_entries
return [
entry for entry in self.field_entries if entry.field.public and entry.value
]
def get_invite_code(self):
from flask import current_app
from CTFd.utils.security.signing import serialize, hmac
secret_key = current_app.config["SECRET_KEY"]
if isinstance(secret_key, str):
secret_key = secret_key.encode("utf-8")
team_password_key = self.password.encode("utf-8")
verification_secret = secret_key + team_password_key
invite_object = {
"id": self.id,
"v": hmac(str(self.id), secret=verification_secret),
}
code = serialize(data=invite_object, secret=secret_key)
return code
def load_invite_code(cls, code):
from flask import current_app
from CTFd.utils.security.signing import (
unserialize,
hmac,
BadTimeSignature,
BadSignature,
)
from CTFd.exceptions import TeamTokenExpiredException, TeamTokenInvalidException
secret_key = current_app.config["SECRET_KEY"]
if isinstance(secret_key, str):
secret_key = secret_key.encode("utf-8")
# Unserialize the invite code
try:
# Links expire after 1 day
invite_object = unserialize(code, max_age=86400)
except BadTimeSignature:
raise TeamTokenExpiredException
except BadSignature:
raise TeamTokenInvalidException
# Load the team by the ID in the invite
team_id = invite_object["id"]
team = cls.query.filter_by(id=team_id).first_or_404()
# Create the team specific secret
team_password_key = team.password.encode("utf-8")
verification_secret = secret_key + team_password_key
# Verify the team verficiation code
verified = hmac(str(team.id), secret=verification_secret) == invite_object["v"]
if verified is False:
raise TeamTokenInvalidException
return team
def get_solves(self, admin=False):
from CTFd.utils import get_config
member_ids = [member.id for member in self.members]
solves = Solves.query.filter(Solves.user_id.in_(member_ids)).order_by(
Solves.date.asc()
)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
solves = solves.filter(Solves.date < dt)
return solves.all()
def get_fails(self, admin=False):
from CTFd.utils import get_config
member_ids = [member.id for member in self.members]
fails = Fails.query.filter(Fails.user_id.in_(member_ids)).order_by(
Fails.date.asc()
)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
fails = fails.filter(Fails.date < dt)
return fails.all()
def get_awards(self, admin=False):
from CTFd.utils import get_config
member_ids = [member.id for member in self.members]
awards = Awards.query.filter(Awards.user_id.in_(member_ids)).order_by(
Awards.date.asc()
)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
awards = awards.filter(Awards.date < dt)
return awards.all()
def get_score(self, admin=False):
score = 0
for member in self.members:
score += member.get_score(admin=admin)
return score
def get_place(self, admin=False, numeric=False):
"""
This method is generally a clone of CTFd.scoreboard.get_standings.
The point being that models.py must be self-reliant and have little
to no imports within the CTFd application as importing from the
application itself will result in a circular import.
"""
from CTFd.utils.scores import get_team_standings
from CTFd.utils.humanize.numbers import ordinalize
standings = get_team_standings(admin=admin)
for i, team in enumerate(standings):
if team.team_id == self.id:
n = i + 1
if numeric:
return n
return ordinalize(n)
else:
return None
def get_infos():
return get_flashed_messages(category_filter=request.endpoint + ".infos")
def get_errors():
return get_flashed_messages(category_filter=request.endpoint + ".errors")
def public(team_id):
infos = get_infos()
errors = get_errors()
team = Teams.query.filter_by(id=team_id, banned=False, hidden=False).first_or_404()
solves = team.get_solves()
awards = team.get_awards()
place = team.place
score = team.score
if errors:
return render_template("teams/public.html", team=team, errors=errors)
if config.is_scoreboard_frozen():
infos.append("Scoreboard has been frozen")
return render_template(
"teams/public.html",
solves=solves,
awards=awards,
team=team,
score=score,
place=place,
score_frozen=config.is_scoreboard_frozen(),
infos=infos,
errors=errors,
) | null |
158,329 | from flask import render_template, request, url_for
from CTFd.admin import admin
from CTFd.models import Challenges, Submissions
from CTFd.utils.decorators import admins_only
from CTFd.utils.helpers.models import build_model_filters
from CTFd.utils.modes import get_model
class Challenges(db.Model):
__tablename__ = "challenges"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80))
description = db.Column(db.Text)
max_attempts = db.Column(db.Integer, default=0)
value = db.Column(db.Integer)
category = db.Column(db.String(80))
type = db.Column(db.String(80))
state = db.Column(db.String(80), nullable=False, default="visible")
requirements = db.Column(db.JSON)
files = db.relationship("ChallengeFiles", backref="challenge")
tags = db.relationship("Tags", backref="challenge")
hints = db.relationship("Hints", backref="challenge")
flags = db.relationship("Flags", backref="challenge")
comments = db.relationship("ChallengeComments", backref="challenge")
class alt_defaultdict(defaultdict):
"""
This slightly modified defaultdict is intended to allow SQLAlchemy to
not fail when querying Challenges that contain a missing challenge type.
e.g. Challenges.query.all() should not fail if `type` is `a_missing_type`
"""
def __missing__(self, key):
return self["standard"]
__mapper_args__ = {
"polymorphic_identity": "standard",
"polymorphic_on": type,
"_polymorphic_map": alt_defaultdict(),
}
def html(self):
from CTFd.utils.config.pages import build_markdown
from CTFd.utils.helpers import markup
return markup(build_markdown(self.description))
def plugin_class(self):
from CTFd.plugins.challenges import get_chal_class
return get_chal_class(self.type)
def __init__(self, *args, **kwargs):
super(Challenges, self).__init__(**kwargs)
def __repr__(self):
return "<Challenge %r>" % self.name
class Submissions(db.Model):
__tablename__ = "submissions"
id = db.Column(db.Integer, primary_key=True)
challenge_id = db.Column(
db.Integer, db.ForeignKey("challenges.id", ondelete="CASCADE")
)
user_id = db.Column(db.Integer, db.ForeignKey("users.id", ondelete="CASCADE"))
team_id = db.Column(db.Integer, db.ForeignKey("teams.id", ondelete="CASCADE"))
ip = db.Column(db.String(46))
provided = db.Column(db.Text)
type = db.Column(db.String(32))
date = db.Column(db.DateTime, default=datetime.datetime.utcnow)
# Relationships
user = db.relationship("Users", foreign_keys="Submissions.user_id", lazy="select")
team = db.relationship("Teams", foreign_keys="Submissions.team_id", lazy="select")
challenge = db.relationship(
"Challenges", foreign_keys="Submissions.challenge_id", lazy="select"
)
__mapper_args__ = {"polymorphic_on": type}
def account_id(self):
from CTFd.utils import get_config
user_mode = get_config("user_mode")
if user_mode == "teams":
return self.team_id
elif user_mode == "users":
return self.user_id
def account(self):
from CTFd.utils import get_config
user_mode = get_config("user_mode")
if user_mode == "teams":
return self.team
elif user_mode == "users":
return self.user
def get_child(type):
child_classes = {
x.polymorphic_identity: x.class_
for x in Submissions.__mapper__.self_and_descendants
}
return child_classes[type]
def __repr__(self):
return f"<Submission id={self.id}, challenge_id={self.challenge_id}, ip={self.ip}, provided={self.provided}>"
def build_model_filters(model, query, field, extra_columns=None):
if extra_columns is None:
extra_columns = {}
filters = []
if query:
# The field exists as an exposed column
if model.__mapper__.has_property(field):
column = getattr(model, field)
if type(column.type) == sqlalchemy.sql.sqltypes.Integer:
_filter = column.op("=")(query)
else:
_filter = column.like(f"%{query}%")
filters.append(_filter)
else:
if field in extra_columns:
column = extra_columns[field]
_filter = column.op("=")(query)
filters.append(_filter)
return filters
def get_model():
if get_config("user_mode") == USERS_MODE:
return Users
elif get_config("user_mode") == TEAMS_MODE:
return Teams
def submissions_listing(submission_type):
filters_by = {}
if submission_type:
filters_by["type"] = submission_type
filters = []
q = request.args.get("q")
field = request.args.get("field")
page = abs(request.args.get("page", 1, type=int))
filters = build_model_filters(
model=Submissions,
query=q,
field=field,
extra_columns={
"challenge_name": Challenges.name,
"account_id": Submissions.account_id,
},
)
Model = get_model()
submissions = (
Submissions.query.filter_by(**filters_by)
.filter(*filters)
.join(Challenges)
.join(Model)
.order_by(Submissions.date.desc())
.paginate(page=page, per_page=50)
)
args = dict(request.args)
args.pop("page", 1)
return render_template(
"admin/submissions.html",
submissions=submissions,
prev_page=url_for(
request.endpoint,
submission_type=submission_type,
page=submissions.prev_num,
**args
),
next_page=url_for(
request.endpoint,
submission_type=submission_type,
page=submissions.next_num,
**args
),
type=submission_type,
q=q,
field=field,
) | null |
158,330 | from flask import render_template
from CTFd.admin import admin
from CTFd.models import Notifications
from CTFd.utils.decorators import admins_only
class Notifications(db.Model):
def html(self):
def __init__(self, *args, **kwargs):
def notifications():
notifs = Notifications.query.order_by(Notifications.id.desc()).all()
return render_template("admin/notifications.html", notifications=notifs) | null |
158,331 | from flask import render_template, request, url_for
from sqlalchemy.sql import not_
from CTFd.admin import admin
from CTFd.models import Challenges, Teams, Tracking
from CTFd.utils.decorators import admins_only
class Teams(db.Model):
__tablename__ = "teams"
__table_args__ = (db.UniqueConstraint("id", "oauth_id"), {})
# Core attributes
id = db.Column(db.Integer, primary_key=True)
oauth_id = db.Column(db.Integer, unique=True)
# Team names are not constrained to be unique to allow for official/unofficial teams.
name = db.Column(db.String(128))
email = db.Column(db.String(128), unique=True)
password = db.Column(db.String(128))
secret = db.Column(db.String(128))
members = db.relationship(
"Users", backref="team", foreign_keys="Users.team_id", lazy="joined"
)
# Supplementary attributes
website = db.Column(db.String(128))
affiliation = db.Column(db.String(128))
country = db.Column(db.String(32))
bracket = db.Column(db.String(32))
hidden = db.Column(db.Boolean, default=False)
banned = db.Column(db.Boolean, default=False)
# Relationship for Users
captain_id = db.Column(db.Integer, db.ForeignKey("users.id", ondelete="SET NULL"))
captain = db.relationship("Users", foreign_keys=[captain_id])
field_entries = db.relationship(
"TeamFieldEntries", foreign_keys="TeamFieldEntries.team_id", lazy="joined"
)
created = db.Column(db.DateTime, default=datetime.datetime.utcnow)
def __init__(self, **kwargs):
super(Teams, self).__init__(**kwargs)
def validate_password(self, key, plaintext):
from CTFd.utils.crypto import hash_password
return hash_password(str(plaintext))
def fields(self):
return self.get_fields(admin=False)
def solves(self):
return self.get_solves(admin=False)
def fails(self):
return self.get_fails(admin=False)
def awards(self):
return self.get_awards(admin=False)
def score(self):
return self.get_score(admin=False)
def place(self):
from CTFd.utils.config.visibility import scores_visible
if scores_visible():
return self.get_place(admin=False)
else:
return None
def get_fields(self, admin=False):
if admin:
return self.field_entries
return [
entry for entry in self.field_entries if entry.field.public and entry.value
]
def get_invite_code(self):
from flask import current_app
from CTFd.utils.security.signing import serialize, hmac
secret_key = current_app.config["SECRET_KEY"]
if isinstance(secret_key, str):
secret_key = secret_key.encode("utf-8")
team_password_key = self.password.encode("utf-8")
verification_secret = secret_key + team_password_key
invite_object = {
"id": self.id,
"v": hmac(str(self.id), secret=verification_secret),
}
code = serialize(data=invite_object, secret=secret_key)
return code
def load_invite_code(cls, code):
from flask import current_app
from CTFd.utils.security.signing import (
unserialize,
hmac,
BadTimeSignature,
BadSignature,
)
from CTFd.exceptions import TeamTokenExpiredException, TeamTokenInvalidException
secret_key = current_app.config["SECRET_KEY"]
if isinstance(secret_key, str):
secret_key = secret_key.encode("utf-8")
# Unserialize the invite code
try:
# Links expire after 1 day
invite_object = unserialize(code, max_age=86400)
except BadTimeSignature:
raise TeamTokenExpiredException
except BadSignature:
raise TeamTokenInvalidException
# Load the team by the ID in the invite
team_id = invite_object["id"]
team = cls.query.filter_by(id=team_id).first_or_404()
# Create the team specific secret
team_password_key = team.password.encode("utf-8")
verification_secret = secret_key + team_password_key
# Verify the team verficiation code
verified = hmac(str(team.id), secret=verification_secret) == invite_object["v"]
if verified is False:
raise TeamTokenInvalidException
return team
def get_solves(self, admin=False):
from CTFd.utils import get_config
member_ids = [member.id for member in self.members]
solves = Solves.query.filter(Solves.user_id.in_(member_ids)).order_by(
Solves.date.asc()
)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
solves = solves.filter(Solves.date < dt)
return solves.all()
def get_fails(self, admin=False):
from CTFd.utils import get_config
member_ids = [member.id for member in self.members]
fails = Fails.query.filter(Fails.user_id.in_(member_ids)).order_by(
Fails.date.asc()
)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
fails = fails.filter(Fails.date < dt)
return fails.all()
def get_awards(self, admin=False):
from CTFd.utils import get_config
member_ids = [member.id for member in self.members]
awards = Awards.query.filter(Awards.user_id.in_(member_ids)).order_by(
Awards.date.asc()
)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
awards = awards.filter(Awards.date < dt)
return awards.all()
def get_score(self, admin=False):
score = 0
for member in self.members:
score += member.get_score(admin=admin)
return score
def get_place(self, admin=False, numeric=False):
"""
This method is generally a clone of CTFd.scoreboard.get_standings.
The point being that models.py must be self-reliant and have little
to no imports within the CTFd application as importing from the
application itself will result in a circular import.
"""
from CTFd.utils.scores import get_team_standings
from CTFd.utils.humanize.numbers import ordinalize
standings = get_team_standings(admin=admin)
for i, team in enumerate(standings):
if team.team_id == self.id:
n = i + 1
if numeric:
return n
return ordinalize(n)
else:
return None
def teams_listing():
q = request.args.get("q")
field = request.args.get("field")
page = abs(request.args.get("page", 1, type=int))
filters = []
if q:
# The field exists as an exposed column
if Teams.__mapper__.has_property(field):
filters.append(getattr(Teams, field).like("%{}%".format(q)))
teams = (
Teams.query.filter(*filters)
.order_by(Teams.id.asc())
.paginate(page=page, per_page=50)
)
args = dict(request.args)
args.pop("page", 1)
return render_template(
"admin/teams/teams.html",
teams=teams,
prev_page=url_for(request.endpoint, page=teams.prev_num, **args),
next_page=url_for(request.endpoint, page=teams.next_num, **args),
q=q,
field=field,
) | null |
158,332 | from flask import render_template, request, url_for
from sqlalchemy.sql import not_
from CTFd.admin import admin
from CTFd.models import Challenges, Teams, Tracking
from CTFd.utils.decorators import admins_only
def teams_new():
return render_template("admin/teams/new.html") | null |
158,333 | from flask import render_template, request, url_for
from sqlalchemy.sql import not_
from CTFd.admin import admin
from CTFd.models import Challenges, Teams, Tracking
from CTFd.utils.decorators import admins_only
admin = Blueprint("admin", __name__)
class Challenges(db.Model):
__tablename__ = "challenges"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80))
description = db.Column(db.Text)
max_attempts = db.Column(db.Integer, default=0)
value = db.Column(db.Integer)
category = db.Column(db.String(80))
type = db.Column(db.String(80))
state = db.Column(db.String(80), nullable=False, default="visible")
requirements = db.Column(db.JSON)
files = db.relationship("ChallengeFiles", backref="challenge")
tags = db.relationship("Tags", backref="challenge")
hints = db.relationship("Hints", backref="challenge")
flags = db.relationship("Flags", backref="challenge")
comments = db.relationship("ChallengeComments", backref="challenge")
class alt_defaultdict(defaultdict):
"""
This slightly modified defaultdict is intended to allow SQLAlchemy to
not fail when querying Challenges that contain a missing challenge type.
e.g. Challenges.query.all() should not fail if `type` is `a_missing_type`
"""
def __missing__(self, key):
return self["standard"]
__mapper_args__ = {
"polymorphic_identity": "standard",
"polymorphic_on": type,
"_polymorphic_map": alt_defaultdict(),
}
def html(self):
from CTFd.utils.config.pages import build_markdown
from CTFd.utils.helpers import markup
return markup(build_markdown(self.description))
def plugin_class(self):
from CTFd.plugins.challenges import get_chal_class
return get_chal_class(self.type)
def __init__(self, *args, **kwargs):
super(Challenges, self).__init__(**kwargs)
def __repr__(self):
return "<Challenge %r>" % self.name
class Teams(db.Model):
__tablename__ = "teams"
__table_args__ = (db.UniqueConstraint("id", "oauth_id"), {})
# Core attributes
id = db.Column(db.Integer, primary_key=True)
oauth_id = db.Column(db.Integer, unique=True)
# Team names are not constrained to be unique to allow for official/unofficial teams.
name = db.Column(db.String(128))
email = db.Column(db.String(128), unique=True)
password = db.Column(db.String(128))
secret = db.Column(db.String(128))
members = db.relationship(
"Users", backref="team", foreign_keys="Users.team_id", lazy="joined"
)
# Supplementary attributes
website = db.Column(db.String(128))
affiliation = db.Column(db.String(128))
country = db.Column(db.String(32))
bracket = db.Column(db.String(32))
hidden = db.Column(db.Boolean, default=False)
banned = db.Column(db.Boolean, default=False)
# Relationship for Users
captain_id = db.Column(db.Integer, db.ForeignKey("users.id", ondelete="SET NULL"))
captain = db.relationship("Users", foreign_keys=[captain_id])
field_entries = db.relationship(
"TeamFieldEntries", foreign_keys="TeamFieldEntries.team_id", lazy="joined"
)
created = db.Column(db.DateTime, default=datetime.datetime.utcnow)
def __init__(self, **kwargs):
super(Teams, self).__init__(**kwargs)
def validate_password(self, key, plaintext):
from CTFd.utils.crypto import hash_password
return hash_password(str(plaintext))
def fields(self):
return self.get_fields(admin=False)
def solves(self):
return self.get_solves(admin=False)
def fails(self):
return self.get_fails(admin=False)
def awards(self):
return self.get_awards(admin=False)
def score(self):
return self.get_score(admin=False)
def place(self):
from CTFd.utils.config.visibility import scores_visible
if scores_visible():
return self.get_place(admin=False)
else:
return None
def get_fields(self, admin=False):
if admin:
return self.field_entries
return [
entry for entry in self.field_entries if entry.field.public and entry.value
]
def get_invite_code(self):
from flask import current_app
from CTFd.utils.security.signing import serialize, hmac
secret_key = current_app.config["SECRET_KEY"]
if isinstance(secret_key, str):
secret_key = secret_key.encode("utf-8")
team_password_key = self.password.encode("utf-8")
verification_secret = secret_key + team_password_key
invite_object = {
"id": self.id,
"v": hmac(str(self.id), secret=verification_secret),
}
code = serialize(data=invite_object, secret=secret_key)
return code
def load_invite_code(cls, code):
from flask import current_app
from CTFd.utils.security.signing import (
unserialize,
hmac,
BadTimeSignature,
BadSignature,
)
from CTFd.exceptions import TeamTokenExpiredException, TeamTokenInvalidException
secret_key = current_app.config["SECRET_KEY"]
if isinstance(secret_key, str):
secret_key = secret_key.encode("utf-8")
# Unserialize the invite code
try:
# Links expire after 1 day
invite_object = unserialize(code, max_age=86400)
except BadTimeSignature:
raise TeamTokenExpiredException
except BadSignature:
raise TeamTokenInvalidException
# Load the team by the ID in the invite
team_id = invite_object["id"]
team = cls.query.filter_by(id=team_id).first_or_404()
# Create the team specific secret
team_password_key = team.password.encode("utf-8")
verification_secret = secret_key + team_password_key
# Verify the team verficiation code
verified = hmac(str(team.id), secret=verification_secret) == invite_object["v"]
if verified is False:
raise TeamTokenInvalidException
return team
def get_solves(self, admin=False):
from CTFd.utils import get_config
member_ids = [member.id for member in self.members]
solves = Solves.query.filter(Solves.user_id.in_(member_ids)).order_by(
Solves.date.asc()
)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
solves = solves.filter(Solves.date < dt)
return solves.all()
def get_fails(self, admin=False):
from CTFd.utils import get_config
member_ids = [member.id for member in self.members]
fails = Fails.query.filter(Fails.user_id.in_(member_ids)).order_by(
Fails.date.asc()
)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
fails = fails.filter(Fails.date < dt)
return fails.all()
def get_awards(self, admin=False):
from CTFd.utils import get_config
member_ids = [member.id for member in self.members]
awards = Awards.query.filter(Awards.user_id.in_(member_ids)).order_by(
Awards.date.asc()
)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
awards = awards.filter(Awards.date < dt)
return awards.all()
def get_score(self, admin=False):
score = 0
for member in self.members:
score += member.get_score(admin=admin)
return score
def get_place(self, admin=False, numeric=False):
"""
This method is generally a clone of CTFd.scoreboard.get_standings.
The point being that models.py must be self-reliant and have little
to no imports within the CTFd application as importing from the
application itself will result in a circular import.
"""
from CTFd.utils.scores import get_team_standings
from CTFd.utils.humanize.numbers import ordinalize
standings = get_team_standings(admin=admin)
for i, team in enumerate(standings):
if team.team_id == self.id:
n = i + 1
if numeric:
return n
return ordinalize(n)
else:
return None
class Tracking(db.Model):
__tablename__ = "tracking"
id = db.Column(db.Integer, primary_key=True)
type = db.Column(db.String(32))
ip = db.Column(db.String(46))
user_id = db.Column(db.Integer, db.ForeignKey("users.id", ondelete="CASCADE"))
date = db.Column(db.DateTime, default=datetime.datetime.utcnow)
user = db.relationship("Users", foreign_keys="Tracking.user_id", lazy="select")
__mapper_args__ = {"polymorphic_on": type}
def __init__(self, *args, **kwargs):
super(Tracking, self).__init__(**kwargs)
def __repr__(self):
return "<Tracking %r>" % self.ip
def teams_detail(team_id):
team = Teams.query.filter_by(id=team_id).first_or_404()
# Get members
members = team.members
member_ids = [member.id for member in members]
# Get Solves for all members
solves = team.get_solves(admin=True)
fails = team.get_fails(admin=True)
awards = team.get_awards(admin=True)
score = team.get_score(admin=True)
place = team.get_place(admin=True)
# Get missing Challenges for all members
# TODO: How do you mark a missing challenge for a team?
solve_ids = [s.challenge_id for s in solves]
missing = Challenges.query.filter(not_(Challenges.id.in_(solve_ids))).all()
# Get addresses for all members
addrs = (
Tracking.query.filter(Tracking.user_id.in_(member_ids))
.order_by(Tracking.date.desc())
.all()
)
return render_template(
"admin/teams/team.html",
team=team,
members=members,
score=score,
place=place,
solves=solves,
fails=fails,
missing=missing,
awards=awards,
addrs=addrs,
) | null |
158,334 | from flask import render_template, request, url_for
from sqlalchemy.sql import not_
from CTFd.admin import admin
from CTFd.models import Challenges, Tracking, Users
from CTFd.utils import get_config
from CTFd.utils.decorators import admins_only
from CTFd.utils.modes import TEAMS_MODE
class Users(db.Model):
__tablename__ = "users"
__table_args__ = (db.UniqueConstraint("id", "oauth_id"), {})
# Core attributes
id = db.Column(db.Integer, primary_key=True)
oauth_id = db.Column(db.Integer, unique=True)
# User names are not constrained to be unique to allow for official/unofficial teams.
name = db.Column(db.String(128))
password = db.Column(db.String(128))
email = db.Column(db.String(128), unique=True)
type = db.Column(db.String(80))
secret = db.Column(db.String(128))
# Supplementary attributes
website = db.Column(db.String(128))
affiliation = db.Column(db.String(128))
country = db.Column(db.String(32))
bracket = db.Column(db.String(32))
hidden = db.Column(db.Boolean, default=False)
banned = db.Column(db.Boolean, default=False)
verified = db.Column(db.Boolean, default=False)
# Relationship for Teams
team_id = db.Column(db.Integer, db.ForeignKey("teams.id"))
field_entries = db.relationship(
"UserFieldEntries", foreign_keys="UserFieldEntries.user_id", lazy="joined"
)
created = db.Column(db.DateTime, default=datetime.datetime.utcnow)
__mapper_args__ = {"polymorphic_identity": "user", "polymorphic_on": type}
def __init__(self, **kwargs):
super(Users, self).__init__(**kwargs)
def validate_password(self, key, plaintext):
from CTFd.utils.crypto import hash_password
return hash_password(str(plaintext))
def account_id(self):
from CTFd.utils import get_config
user_mode = get_config("user_mode")
if user_mode == "teams":
return self.team_id
elif user_mode == "users":
return self.id
def account(self):
from CTFd.utils import get_config
user_mode = get_config("user_mode")
if user_mode == "teams":
return self.team
elif user_mode == "users":
return self
def fields(self):
return self.get_fields(admin=False)
def solves(self):
return self.get_solves(admin=False)
def fails(self):
return self.get_fails(admin=False)
def awards(self):
return self.get_awards(admin=False)
def score(self):
return self.get_score(admin=False)
def place(self):
from CTFd.utils.config.visibility import scores_visible
if scores_visible():
return self.get_place(admin=False)
else:
return None
def get_fields(self, admin=False):
if admin:
return self.field_entries
return [
entry for entry in self.field_entries if entry.field.public and entry.value
]
def get_solves(self, admin=False):
from CTFd.utils import get_config
solves = Solves.query.filter_by(user_id=self.id)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
solves = solves.filter(Solves.date < dt)
return solves.all()
def get_fails(self, admin=False):
from CTFd.utils import get_config
fails = Fails.query.filter_by(user_id=self.id)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
fails = fails.filter(Fails.date < dt)
return fails.all()
def get_awards(self, admin=False):
from CTFd.utils import get_config
awards = Awards.query.filter_by(user_id=self.id)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
awards = awards.filter(Awards.date < dt)
return awards.all()
def get_score(self, admin=False):
score = db.func.sum(Challenges.value).label("score")
user = (
db.session.query(Solves.user_id, score)
.join(Users, Solves.user_id == Users.id)
.join(Challenges, Solves.challenge_id == Challenges.id)
.filter(Users.id == self.id)
)
award_score = db.func.sum(Awards.value).label("award_score")
award = db.session.query(award_score).filter_by(user_id=self.id)
if not admin:
freeze = Configs.query.filter_by(key="freeze").first()
if freeze and freeze.value:
freeze = int(freeze.value)
freeze = datetime.datetime.utcfromtimestamp(freeze)
user = user.filter(Solves.date < freeze)
award = award.filter(Awards.date < freeze)
user = user.group_by(Solves.user_id).first()
award = award.first()
if user and award:
return int(user.score or 0) + int(award.award_score or 0)
elif user:
return int(user.score or 0)
elif award:
return int(award.award_score or 0)
else:
return 0
def get_place(self, admin=False, numeric=False):
"""
This method is generally a clone of CTFd.scoreboard.get_standings.
The point being that models.py must be self-reliant and have little
to no imports within the CTFd application as importing from the
application itself will result in a circular import.
"""
from CTFd.utils.scores import get_user_standings
from CTFd.utils.humanize.numbers import ordinalize
standings = get_user_standings(admin=admin)
for i, user in enumerate(standings):
if user.user_id == self.id:
n = i + 1
if numeric:
return n
return ordinalize(n)
else:
return None
class Tracking(db.Model):
__tablename__ = "tracking"
id = db.Column(db.Integer, primary_key=True)
type = db.Column(db.String(32))
ip = db.Column(db.String(46))
user_id = db.Column(db.Integer, db.ForeignKey("users.id", ondelete="CASCADE"))
date = db.Column(db.DateTime, default=datetime.datetime.utcnow)
user = db.relationship("Users", foreign_keys="Tracking.user_id", lazy="select")
__mapper_args__ = {"polymorphic_on": type}
def __init__(self, *args, **kwargs):
super(Tracking, self).__init__(**kwargs)
def __repr__(self):
return "<Tracking %r>" % self.ip
def users_listing():
q = request.args.get("q")
field = request.args.get("field")
page = abs(request.args.get("page", 1, type=int))
filters = []
users = []
if q:
# The field exists as an exposed column
if Users.__mapper__.has_property(field):
filters.append(getattr(Users, field).like("%{}%".format(q)))
if q and field == "ip":
users = (
Users.query.join(Tracking, Users.id == Tracking.user_id)
.filter(Tracking.ip.like("%{}%".format(q)))
.order_by(Users.id.asc())
.paginate(page=page, per_page=50)
)
else:
users = (
Users.query.filter(*filters)
.order_by(Users.id.asc())
.paginate(page=page, per_page=50)
)
args = dict(request.args)
args.pop("page", 1)
return render_template(
"admin/users/users.html",
users=users,
prev_page=url_for(request.endpoint, page=users.prev_num, **args),
next_page=url_for(request.endpoint, page=users.next_num, **args),
q=q,
field=field,
) | null |
158,335 | from flask import render_template, request, url_for
from sqlalchemy.sql import not_
from CTFd.admin import admin
from CTFd.models import Challenges, Tracking, Users
from CTFd.utils import get_config
from CTFd.utils.decorators import admins_only
from CTFd.utils.modes import TEAMS_MODE
def users_new():
return render_template("admin/users/new.html") | null |
158,336 | from flask import render_template, request, url_for
from sqlalchemy.sql import not_
from CTFd.admin import admin
from CTFd.models import Challenges, Tracking, Users
from CTFd.utils import get_config
from CTFd.utils.decorators import admins_only
from CTFd.utils.modes import TEAMS_MODE
admin = Blueprint("admin", __name__)
class Challenges(db.Model):
__tablename__ = "challenges"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80))
description = db.Column(db.Text)
max_attempts = db.Column(db.Integer, default=0)
value = db.Column(db.Integer)
category = db.Column(db.String(80))
type = db.Column(db.String(80))
state = db.Column(db.String(80), nullable=False, default="visible")
requirements = db.Column(db.JSON)
files = db.relationship("ChallengeFiles", backref="challenge")
tags = db.relationship("Tags", backref="challenge")
hints = db.relationship("Hints", backref="challenge")
flags = db.relationship("Flags", backref="challenge")
comments = db.relationship("ChallengeComments", backref="challenge")
class alt_defaultdict(defaultdict):
"""
This slightly modified defaultdict is intended to allow SQLAlchemy to
not fail when querying Challenges that contain a missing challenge type.
e.g. Challenges.query.all() should not fail if `type` is `a_missing_type`
"""
def __missing__(self, key):
return self["standard"]
__mapper_args__ = {
"polymorphic_identity": "standard",
"polymorphic_on": type,
"_polymorphic_map": alt_defaultdict(),
}
def html(self):
from CTFd.utils.config.pages import build_markdown
from CTFd.utils.helpers import markup
return markup(build_markdown(self.description))
def plugin_class(self):
from CTFd.plugins.challenges import get_chal_class
return get_chal_class(self.type)
def __init__(self, *args, **kwargs):
super(Challenges, self).__init__(**kwargs)
def __repr__(self):
return "<Challenge %r>" % self.name
class Users(db.Model):
__tablename__ = "users"
__table_args__ = (db.UniqueConstraint("id", "oauth_id"), {})
# Core attributes
id = db.Column(db.Integer, primary_key=True)
oauth_id = db.Column(db.Integer, unique=True)
# User names are not constrained to be unique to allow for official/unofficial teams.
name = db.Column(db.String(128))
password = db.Column(db.String(128))
email = db.Column(db.String(128), unique=True)
type = db.Column(db.String(80))
secret = db.Column(db.String(128))
# Supplementary attributes
website = db.Column(db.String(128))
affiliation = db.Column(db.String(128))
country = db.Column(db.String(32))
bracket = db.Column(db.String(32))
hidden = db.Column(db.Boolean, default=False)
banned = db.Column(db.Boolean, default=False)
verified = db.Column(db.Boolean, default=False)
# Relationship for Teams
team_id = db.Column(db.Integer, db.ForeignKey("teams.id"))
field_entries = db.relationship(
"UserFieldEntries", foreign_keys="UserFieldEntries.user_id", lazy="joined"
)
created = db.Column(db.DateTime, default=datetime.datetime.utcnow)
__mapper_args__ = {"polymorphic_identity": "user", "polymorphic_on": type}
def __init__(self, **kwargs):
super(Users, self).__init__(**kwargs)
def validate_password(self, key, plaintext):
from CTFd.utils.crypto import hash_password
return hash_password(str(plaintext))
def account_id(self):
from CTFd.utils import get_config
user_mode = get_config("user_mode")
if user_mode == "teams":
return self.team_id
elif user_mode == "users":
return self.id
def account(self):
from CTFd.utils import get_config
user_mode = get_config("user_mode")
if user_mode == "teams":
return self.team
elif user_mode == "users":
return self
def fields(self):
return self.get_fields(admin=False)
def solves(self):
return self.get_solves(admin=False)
def fails(self):
return self.get_fails(admin=False)
def awards(self):
return self.get_awards(admin=False)
def score(self):
return self.get_score(admin=False)
def place(self):
from CTFd.utils.config.visibility import scores_visible
if scores_visible():
return self.get_place(admin=False)
else:
return None
def get_fields(self, admin=False):
if admin:
return self.field_entries
return [
entry for entry in self.field_entries if entry.field.public and entry.value
]
def get_solves(self, admin=False):
from CTFd.utils import get_config
solves = Solves.query.filter_by(user_id=self.id)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
solves = solves.filter(Solves.date < dt)
return solves.all()
def get_fails(self, admin=False):
from CTFd.utils import get_config
fails = Fails.query.filter_by(user_id=self.id)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
fails = fails.filter(Fails.date < dt)
return fails.all()
def get_awards(self, admin=False):
from CTFd.utils import get_config
awards = Awards.query.filter_by(user_id=self.id)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
awards = awards.filter(Awards.date < dt)
return awards.all()
def get_score(self, admin=False):
score = db.func.sum(Challenges.value).label("score")
user = (
db.session.query(Solves.user_id, score)
.join(Users, Solves.user_id == Users.id)
.join(Challenges, Solves.challenge_id == Challenges.id)
.filter(Users.id == self.id)
)
award_score = db.func.sum(Awards.value).label("award_score")
award = db.session.query(award_score).filter_by(user_id=self.id)
if not admin:
freeze = Configs.query.filter_by(key="freeze").first()
if freeze and freeze.value:
freeze = int(freeze.value)
freeze = datetime.datetime.utcfromtimestamp(freeze)
user = user.filter(Solves.date < freeze)
award = award.filter(Awards.date < freeze)
user = user.group_by(Solves.user_id).first()
award = award.first()
if user and award:
return int(user.score or 0) + int(award.award_score or 0)
elif user:
return int(user.score or 0)
elif award:
return int(award.award_score or 0)
else:
return 0
def get_place(self, admin=False, numeric=False):
"""
This method is generally a clone of CTFd.scoreboard.get_standings.
The point being that models.py must be self-reliant and have little
to no imports within the CTFd application as importing from the
application itself will result in a circular import.
"""
from CTFd.utils.scores import get_user_standings
from CTFd.utils.humanize.numbers import ordinalize
standings = get_user_standings(admin=admin)
for i, user in enumerate(standings):
if user.user_id == self.id:
n = i + 1
if numeric:
return n
return ordinalize(n)
else:
return None
class Tracking(db.Model):
__tablename__ = "tracking"
id = db.Column(db.Integer, primary_key=True)
type = db.Column(db.String(32))
ip = db.Column(db.String(46))
user_id = db.Column(db.Integer, db.ForeignKey("users.id", ondelete="CASCADE"))
date = db.Column(db.DateTime, default=datetime.datetime.utcnow)
user = db.relationship("Users", foreign_keys="Tracking.user_id", lazy="select")
__mapper_args__ = {"polymorphic_on": type}
def __init__(self, *args, **kwargs):
super(Tracking, self).__init__(**kwargs)
def __repr__(self):
return "<Tracking %r>" % self.ip
def get_config(key, default=None):
# Convert enums to raw string values to cache better
if isinstance(key, Enum):
key = str(key)
value = _get_config(key)
if value is KeyError:
return default
else:
return value
TEAMS_MODE = "teams"
def users_detail(user_id):
# Get user object
user = Users.query.filter_by(id=user_id).first_or_404()
# Get the user's solves
solves = user.get_solves(admin=True)
# Get challenges that the user is missing
if get_config("user_mode") == TEAMS_MODE:
if user.team:
all_solves = user.team.get_solves(admin=True)
else:
all_solves = user.get_solves(admin=True)
else:
all_solves = user.get_solves(admin=True)
solve_ids = [s.challenge_id for s in all_solves]
missing = Challenges.query.filter(not_(Challenges.id.in_(solve_ids))).all()
# Get IP addresses that the User has used
addrs = (
Tracking.query.filter_by(user_id=user_id).order_by(Tracking.date.desc()).all()
)
# Get Fails
fails = user.get_fails(admin=True)
# Get Awards
awards = user.get_awards(admin=True)
# Check if the user has an account (team or user)
# so that we don't throw an error if they dont
if user.account:
score = user.account.get_score(admin=True)
place = user.account.get_place(admin=True)
else:
score = None
place = None
return render_template(
"admin/users/user.html",
solves=solves,
user=user,
addrs=addrs,
score=score,
missing=missing,
place=place,
fails=fails,
awards=awards,
) | null |
158,337 | from flask import render_template, request
from CTFd.admin import admin
from CTFd.models import Pages
from CTFd.schemas.pages import PageSchema
from CTFd.utils import markdown
from CTFd.utils.decorators import admins_only
class Pages(db.Model):
__tablename__ = "pages"
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(80))
route = db.Column(db.String(128), unique=True)
content = db.Column(db.Text)
draft = db.Column(db.Boolean)
hidden = db.Column(db.Boolean)
auth_required = db.Column(db.Boolean)
format = db.Column(db.String(80), default="markdown")
# TODO: Use hidden attribute
files = db.relationship("PageFiles", backref="page")
def html(self):
from CTFd.utils.config.pages import build_html, build_markdown
if self.format == "markdown":
return build_markdown(self.content)
elif self.format == "html":
return build_html(self.content)
else:
return build_markdown(self.content)
def __init__(self, *args, **kwargs):
super(Pages, self).__init__(**kwargs)
def __repr__(self):
return "<Pages {0}>".format(self.route)
def pages_listing():
pages = Pages.query.all()
return render_template("admin/pages.html", pages=pages) | null |
158,338 | from flask import render_template, request
from CTFd.admin import admin
from CTFd.models import Pages
from CTFd.schemas.pages import PageSchema
from CTFd.utils import markdown
from CTFd.utils.decorators import admins_only
def pages_new():
return render_template("admin/editor.html") | null |
158,339 | from flask import render_template, request
from CTFd.admin import admin
from CTFd.models import Pages
from CTFd.schemas.pages import PageSchema
from CTFd.utils import markdown
from CTFd.utils.decorators import admins_only
class PageSchema(ma.ModelSchema):
class Meta:
model = Pages
include_fk = True
dump_only = ("id",)
title = field_for(
Pages,
"title",
validate=[
validate.Length(
min=0, max=80, error="Page could not be saved. Your title is too long.",
)
],
)
route = field_for(
Pages,
"route",
allow_none=True,
validate=[
validate.Length(
min=0,
max=128,
error="Page could not be saved. Your route is too long.",
)
],
)
content = field_for(
Pages,
"content",
allow_none=True,
validate=[
validate.Length(
min=0,
max=65535,
error="Page could not be saved. Your content is too long.",
)
],
)
def validate_route(self, data):
route = data.get("route")
if route and route.startswith("/"):
data["route"] = route.strip("/")
def __init__(self, view=None, *args, **kwargs):
if view:
if isinstance(view, string_types):
kwargs["only"] = self.views[view]
elif isinstance(view, list):
kwargs["only"] = view
super(PageSchema, self).__init__(*args, **kwargs)
def pages_preview():
# We only care about content.
# Loading other attributes improperly will cause Marshmallow to incorrectly return a dict
data = {"content": request.form.get("content")}
schema = PageSchema()
page = schema.load(data)
return render_template("page.html", content=page.data.html) | null |
158,340 | from flask import render_template, request
from CTFd.admin import admin
from CTFd.models import Pages
from CTFd.schemas.pages import PageSchema
from CTFd.utils import markdown
from CTFd.utils.decorators import admins_only
class Pages(db.Model):
def html(self):
def __init__(self, *args, **kwargs):
def __repr__(self):
def markdown(md):
def pages_detail(page_id):
page = Pages.query.filter_by(id=page_id).first_or_404()
page_op = request.args.get("operation")
if request.method == "GET" and page_op == "preview":
return render_template("page.html", content=markdown(page.content))
if request.method == "GET" and page_op == "create":
return render_template("admin/editor.html")
return render_template("admin/editor.html", page=page) | null |
158,341 | from flask import render_template
from CTFd.admin import admin
from CTFd.utils.config import is_teams_mode
from CTFd.utils.decorators import admins_only
from CTFd.utils.scores import get_standings, get_user_standings
admin = Blueprint("admin", __name__)
def is_teams_mode():
return user_mode() == TEAMS_MODE
def get_standings(count=None, admin=False, fields=None):
"""
Get standings as a list of tuples containing account_id, name, and score e.g. [(account_id, team_name, score)].
Ties are broken by who reached a given score first based on the solve ID. Two users can have the same score but one
user will have a solve ID that is before the others. That user will be considered the tie-winner.
Challenges & Awards with a value of zero are filtered out of the calculations to avoid incorrect tie breaks.
"""
if fields is None:
fields = []
Model = get_model()
scores = (
db.session.query(
Solves.account_id.label("account_id"),
db.func.sum(Challenges.value).label("score"),
db.func.max(Solves.id).label("id"),
db.func.max(Solves.date).label("date"),
)
.join(Challenges)
.filter(Challenges.value != 0)
.group_by(Solves.account_id)
)
awards = (
db.session.query(
Awards.account_id.label("account_id"),
db.func.sum(Awards.value).label("score"),
db.func.max(Awards.id).label("id"),
db.func.max(Awards.date).label("date"),
)
.filter(Awards.value != 0)
.group_by(Awards.account_id)
)
"""
Filter out solves and awards that are before a specific time point.
"""
freeze = get_config("freeze")
if not admin and freeze:
scores = scores.filter(Solves.date < unix_time_to_utc(freeze))
awards = awards.filter(Awards.date < unix_time_to_utc(freeze))
"""
Combine awards and solves with a union. They should have the same amount of columns
"""
results = union_all(scores, awards).alias("results")
"""
Sum each of the results by the team id to get their score.
"""
sumscores = (
db.session.query(
results.columns.account_id,
db.func.sum(results.columns.score).label("score"),
db.func.max(results.columns.id).label("id"),
db.func.max(results.columns.date).label("date"),
)
.group_by(results.columns.account_id)
.subquery()
)
"""
Admins can see scores for all users but the public cannot see banned users.
Filters out banned users.
Properly resolves value ties by ID.
Different databases treat time precision differently so resolve by the row ID instead.
"""
if admin:
standings_query = (
db.session.query(
Model.id.label("account_id"),
Model.oauth_id.label("oauth_id"),
Model.name.label("name"),
Model.hidden,
Model.banned,
sumscores.columns.score,
*fields,
)
.join(sumscores, Model.id == sumscores.columns.account_id)
.order_by(sumscores.columns.score.desc(), sumscores.columns.id)
)
else:
standings_query = (
db.session.query(
Model.id.label("account_id"),
Model.oauth_id.label("oauth_id"),
Model.name.label("name"),
sumscores.columns.score,
*fields,
)
.join(sumscores, Model.id == sumscores.columns.account_id)
.filter(Model.banned == False, Model.hidden == False)
.order_by(sumscores.columns.score.desc(), sumscores.columns.id)
)
"""
Only select a certain amount of users if asked.
"""
if count is None:
standings = standings_query.all()
else:
standings = standings_query.limit(count).all()
return standings
def get_user_standings(count=None, admin=False, fields=None):
if fields is None:
fields = []
scores = (
db.session.query(
Solves.user_id.label("user_id"),
db.func.sum(Challenges.value).label("score"),
db.func.max(Solves.id).label("id"),
db.func.max(Solves.date).label("date"),
)
.join(Challenges)
.filter(Challenges.value != 0)
.group_by(Solves.user_id)
)
awards = (
db.session.query(
Awards.user_id.label("user_id"),
db.func.sum(Awards.value).label("score"),
db.func.max(Awards.id).label("id"),
db.func.max(Awards.date).label("date"),
)
.filter(Awards.value != 0)
.group_by(Awards.user_id)
)
freeze = get_config("freeze")
if not admin and freeze:
scores = scores.filter(Solves.date < unix_time_to_utc(freeze))
awards = awards.filter(Awards.date < unix_time_to_utc(freeze))
results = union_all(scores, awards).alias("results")
sumscores = (
db.session.query(
results.columns.user_id,
db.func.sum(results.columns.score).label("score"),
db.func.max(results.columns.id).label("id"),
db.func.max(results.columns.date).label("date"),
)
.group_by(results.columns.user_id)
.subquery()
)
if admin:
standings_query = (
db.session.query(
Users.id.label("user_id"),
Users.oauth_id.label("oauth_id"),
Users.name.label("name"),
Users.team_id.label("team_id"),
Users.hidden,
Users.banned,
sumscores.columns.score,
*fields,
)
.join(sumscores, Users.id == sumscores.columns.user_id)
.order_by(sumscores.columns.score.desc(), sumscores.columns.id)
)
else:
standings_query = (
db.session.query(
Users.id.label("user_id"),
Users.oauth_id.label("oauth_id"),
Users.name.label("name"),
Users.team_id.label("team_id"),
sumscores.columns.score,
*fields,
)
.join(sumscores, Users.id == sumscores.columns.user_id)
.filter(Users.banned == False, Users.hidden == False)
.order_by(sumscores.columns.score.desc(), sumscores.columns.id)
)
if count is None:
standings = standings_query.all()
else:
standings = standings_query.limit(count).all()
return standings
def scoreboard_listing():
standings = get_standings(admin=True)
user_standings = get_user_standings(admin=True) if is_teams_mode() else None
return render_template(
"admin/scoreboard.html", standings=standings, user_standings=user_standings
) | null |
158,342 | from flask import abort, render_template, request, url_for
from CTFd.admin import admin
from CTFd.models import Challenges, Flags, Solves
from CTFd.plugins.challenges import CHALLENGE_CLASSES, get_chal_class
from CTFd.utils.decorators import admins_only
class Challenges(db.Model):
__tablename__ = "challenges"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80))
description = db.Column(db.Text)
max_attempts = db.Column(db.Integer, default=0)
value = db.Column(db.Integer)
category = db.Column(db.String(80))
type = db.Column(db.String(80))
state = db.Column(db.String(80), nullable=False, default="visible")
requirements = db.Column(db.JSON)
files = db.relationship("ChallengeFiles", backref="challenge")
tags = db.relationship("Tags", backref="challenge")
hints = db.relationship("Hints", backref="challenge")
flags = db.relationship("Flags", backref="challenge")
comments = db.relationship("ChallengeComments", backref="challenge")
class alt_defaultdict(defaultdict):
"""
This slightly modified defaultdict is intended to allow SQLAlchemy to
not fail when querying Challenges that contain a missing challenge type.
e.g. Challenges.query.all() should not fail if `type` is `a_missing_type`
"""
def __missing__(self, key):
return self["standard"]
__mapper_args__ = {
"polymorphic_identity": "standard",
"polymorphic_on": type,
"_polymorphic_map": alt_defaultdict(),
}
def html(self):
from CTFd.utils.config.pages import build_markdown
from CTFd.utils.helpers import markup
return markup(build_markdown(self.description))
def plugin_class(self):
from CTFd.plugins.challenges import get_chal_class
return get_chal_class(self.type)
def __init__(self, *args, **kwargs):
super(Challenges, self).__init__(**kwargs)
def __repr__(self):
return "<Challenge %r>" % self.name
def challenges_listing():
q = request.args.get("q")
field = request.args.get("field")
filters = []
if q:
# The field exists as an exposed column
if Challenges.__mapper__.has_property(field):
filters.append(getattr(Challenges, field).like("%{}%".format(q)))
query = Challenges.query.filter(*filters).order_by(Challenges.id.asc())
challenges = query.all()
total = query.count()
return render_template(
"admin/challenges/challenges.html",
challenges=challenges,
total=total,
q=q,
field=field,
) | null |
158,343 | from flask import abort, render_template, request, url_for
from CTFd.admin import admin
from CTFd.models import Challenges, Flags, Solves
from CTFd.plugins.challenges import CHALLENGE_CLASSES, get_chal_class
from CTFd.utils.decorators import admins_only
class Challenges(db.Model):
__tablename__ = "challenges"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80))
description = db.Column(db.Text)
max_attempts = db.Column(db.Integer, default=0)
value = db.Column(db.Integer)
category = db.Column(db.String(80))
type = db.Column(db.String(80))
state = db.Column(db.String(80), nullable=False, default="visible")
requirements = db.Column(db.JSON)
files = db.relationship("ChallengeFiles", backref="challenge")
tags = db.relationship("Tags", backref="challenge")
hints = db.relationship("Hints", backref="challenge")
flags = db.relationship("Flags", backref="challenge")
comments = db.relationship("ChallengeComments", backref="challenge")
class alt_defaultdict(defaultdict):
"""
This slightly modified defaultdict is intended to allow SQLAlchemy to
not fail when querying Challenges that contain a missing challenge type.
e.g. Challenges.query.all() should not fail if `type` is `a_missing_type`
"""
def __missing__(self, key):
return self["standard"]
__mapper_args__ = {
"polymorphic_identity": "standard",
"polymorphic_on": type,
"_polymorphic_map": alt_defaultdict(),
}
def html(self):
from CTFd.utils.config.pages import build_markdown
from CTFd.utils.helpers import markup
return markup(build_markdown(self.description))
def plugin_class(self):
from CTFd.plugins.challenges import get_chal_class
return get_chal_class(self.type)
def __init__(self, *args, **kwargs):
super(Challenges, self).__init__(**kwargs)
def __repr__(self):
return "<Challenge %r>" % self.name
class Flags(db.Model):
__tablename__ = "flags"
id = db.Column(db.Integer, primary_key=True)
challenge_id = db.Column(
db.Integer, db.ForeignKey("challenges.id", ondelete="CASCADE")
)
type = db.Column(db.String(80))
content = db.Column(db.Text)
data = db.Column(db.Text)
__mapper_args__ = {"polymorphic_on": type}
def __init__(self, *args, **kwargs):
super(Flags, self).__init__(**kwargs)
def __repr__(self):
return "<Flag {0} for challenge {1}>".format(self.content, self.challenge_id)
class Solves(Submissions):
__tablename__ = "solves"
__table_args__ = (
db.UniqueConstraint("challenge_id", "user_id"),
db.UniqueConstraint("challenge_id", "team_id"),
{},
)
id = db.Column(
None, db.ForeignKey("submissions.id", ondelete="CASCADE"), primary_key=True
)
challenge_id = column_property(
db.Column(db.Integer, db.ForeignKey("challenges.id", ondelete="CASCADE")),
Submissions.challenge_id,
)
user_id = column_property(
db.Column(db.Integer, db.ForeignKey("users.id", ondelete="CASCADE")),
Submissions.user_id,
)
team_id = column_property(
db.Column(db.Integer, db.ForeignKey("teams.id", ondelete="CASCADE")),
Submissions.team_id,
)
user = db.relationship("Users", foreign_keys="Solves.user_id", lazy="select")
team = db.relationship("Teams", foreign_keys="Solves.team_id", lazy="select")
challenge = db.relationship(
"Challenges", foreign_keys="Solves.challenge_id", lazy="select"
)
__mapper_args__ = {"polymorphic_identity": "correct"}
def get_chal_class(class_id):
"""
Utility function used to get the corresponding class from a class ID.
:param class_id: String representing the class ID
:return: Challenge class
"""
cls = CHALLENGE_CLASSES.get(class_id)
if cls is None:
raise KeyError
return cls
def challenges_detail(challenge_id):
challenges = dict(
Challenges.query.with_entities(Challenges.id, Challenges.name).all()
)
challenge = Challenges.query.filter_by(id=challenge_id).first_or_404()
solves = (
Solves.query.filter_by(challenge_id=challenge.id)
.order_by(Solves.date.asc())
.all()
)
flags = Flags.query.filter_by(challenge_id=challenge.id).all()
try:
challenge_class = get_chal_class(challenge.type)
except KeyError:
abort(
500,
f"The underlying challenge type ({challenge.type}) is not installed. This challenge can not be loaded.",
)
update_j2 = render_template(
challenge_class.templates["update"].lstrip("/"), challenge=challenge
)
update_script = url_for(
"views.static_html", route=challenge_class.scripts["update"].lstrip("/")
)
return render_template(
"admin/challenges/challenge.html",
update_template=update_j2,
update_script=update_script,
challenge=challenge,
challenges=challenges,
solves=solves,
flags=flags,
) | null |
158,344 | from flask import abort, render_template, request, url_for
from CTFd.admin import admin
from CTFd.models import Challenges, Flags, Solves
from CTFd.plugins.challenges import CHALLENGE_CLASSES, get_chal_class
from CTFd.utils.decorators import admins_only
CHALLENGE_CLASSES = {"standard": CTFdStandardChallenge}
def challenges_new():
types = CHALLENGE_CLASSES.keys()
return render_template("admin/challenges/new.html", types=types) | null |
158,345 | from flask import render_template
from CTFd.admin import admin
from CTFd.models import Challenges, Fails, Solves, Teams, Tracking, Users, db
from CTFd.utils.decorators import admins_only
from CTFd.utils.modes import get_model
from CTFd.utils.updates import update_check
db = SQLAlchemy()
class Challenges(db.Model):
__tablename__ = "challenges"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80))
description = db.Column(db.Text)
max_attempts = db.Column(db.Integer, default=0)
value = db.Column(db.Integer)
category = db.Column(db.String(80))
type = db.Column(db.String(80))
state = db.Column(db.String(80), nullable=False, default="visible")
requirements = db.Column(db.JSON)
files = db.relationship("ChallengeFiles", backref="challenge")
tags = db.relationship("Tags", backref="challenge")
hints = db.relationship("Hints", backref="challenge")
flags = db.relationship("Flags", backref="challenge")
comments = db.relationship("ChallengeComments", backref="challenge")
class alt_defaultdict(defaultdict):
"""
This slightly modified defaultdict is intended to allow SQLAlchemy to
not fail when querying Challenges that contain a missing challenge type.
e.g. Challenges.query.all() should not fail if `type` is `a_missing_type`
"""
def __missing__(self, key):
return self["standard"]
__mapper_args__ = {
"polymorphic_identity": "standard",
"polymorphic_on": type,
"_polymorphic_map": alt_defaultdict(),
}
def html(self):
from CTFd.utils.config.pages import build_markdown
from CTFd.utils.helpers import markup
return markup(build_markdown(self.description))
def plugin_class(self):
from CTFd.plugins.challenges import get_chal_class
return get_chal_class(self.type)
def __init__(self, *args, **kwargs):
super(Challenges, self).__init__(**kwargs)
def __repr__(self):
return "<Challenge %r>" % self.name
class Users(db.Model):
__tablename__ = "users"
__table_args__ = (db.UniqueConstraint("id", "oauth_id"), {})
# Core attributes
id = db.Column(db.Integer, primary_key=True)
oauth_id = db.Column(db.Integer, unique=True)
# User names are not constrained to be unique to allow for official/unofficial teams.
name = db.Column(db.String(128))
password = db.Column(db.String(128))
email = db.Column(db.String(128), unique=True)
type = db.Column(db.String(80))
secret = db.Column(db.String(128))
# Supplementary attributes
website = db.Column(db.String(128))
affiliation = db.Column(db.String(128))
country = db.Column(db.String(32))
bracket = db.Column(db.String(32))
hidden = db.Column(db.Boolean, default=False)
banned = db.Column(db.Boolean, default=False)
verified = db.Column(db.Boolean, default=False)
# Relationship for Teams
team_id = db.Column(db.Integer, db.ForeignKey("teams.id"))
field_entries = db.relationship(
"UserFieldEntries", foreign_keys="UserFieldEntries.user_id", lazy="joined"
)
created = db.Column(db.DateTime, default=datetime.datetime.utcnow)
__mapper_args__ = {"polymorphic_identity": "user", "polymorphic_on": type}
def __init__(self, **kwargs):
super(Users, self).__init__(**kwargs)
def validate_password(self, key, plaintext):
from CTFd.utils.crypto import hash_password
return hash_password(str(plaintext))
def account_id(self):
from CTFd.utils import get_config
user_mode = get_config("user_mode")
if user_mode == "teams":
return self.team_id
elif user_mode == "users":
return self.id
def account(self):
from CTFd.utils import get_config
user_mode = get_config("user_mode")
if user_mode == "teams":
return self.team
elif user_mode == "users":
return self
def fields(self):
return self.get_fields(admin=False)
def solves(self):
return self.get_solves(admin=False)
def fails(self):
return self.get_fails(admin=False)
def awards(self):
return self.get_awards(admin=False)
def score(self):
return self.get_score(admin=False)
def place(self):
from CTFd.utils.config.visibility import scores_visible
if scores_visible():
return self.get_place(admin=False)
else:
return None
def get_fields(self, admin=False):
if admin:
return self.field_entries
return [
entry for entry in self.field_entries if entry.field.public and entry.value
]
def get_solves(self, admin=False):
from CTFd.utils import get_config
solves = Solves.query.filter_by(user_id=self.id)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
solves = solves.filter(Solves.date < dt)
return solves.all()
def get_fails(self, admin=False):
from CTFd.utils import get_config
fails = Fails.query.filter_by(user_id=self.id)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
fails = fails.filter(Fails.date < dt)
return fails.all()
def get_awards(self, admin=False):
from CTFd.utils import get_config
awards = Awards.query.filter_by(user_id=self.id)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
awards = awards.filter(Awards.date < dt)
return awards.all()
def get_score(self, admin=False):
score = db.func.sum(Challenges.value).label("score")
user = (
db.session.query(Solves.user_id, score)
.join(Users, Solves.user_id == Users.id)
.join(Challenges, Solves.challenge_id == Challenges.id)
.filter(Users.id == self.id)
)
award_score = db.func.sum(Awards.value).label("award_score")
award = db.session.query(award_score).filter_by(user_id=self.id)
if not admin:
freeze = Configs.query.filter_by(key="freeze").first()
if freeze and freeze.value:
freeze = int(freeze.value)
freeze = datetime.datetime.utcfromtimestamp(freeze)
user = user.filter(Solves.date < freeze)
award = award.filter(Awards.date < freeze)
user = user.group_by(Solves.user_id).first()
award = award.first()
if user and award:
return int(user.score or 0) + int(award.award_score or 0)
elif user:
return int(user.score or 0)
elif award:
return int(award.award_score or 0)
else:
return 0
def get_place(self, admin=False, numeric=False):
"""
This method is generally a clone of CTFd.scoreboard.get_standings.
The point being that models.py must be self-reliant and have little
to no imports within the CTFd application as importing from the
application itself will result in a circular import.
"""
from CTFd.utils.scores import get_user_standings
from CTFd.utils.humanize.numbers import ordinalize
standings = get_user_standings(admin=admin)
for i, user in enumerate(standings):
if user.user_id == self.id:
n = i + 1
if numeric:
return n
return ordinalize(n)
else:
return None
class Teams(db.Model):
__tablename__ = "teams"
__table_args__ = (db.UniqueConstraint("id", "oauth_id"), {})
# Core attributes
id = db.Column(db.Integer, primary_key=True)
oauth_id = db.Column(db.Integer, unique=True)
# Team names are not constrained to be unique to allow for official/unofficial teams.
name = db.Column(db.String(128))
email = db.Column(db.String(128), unique=True)
password = db.Column(db.String(128))
secret = db.Column(db.String(128))
members = db.relationship(
"Users", backref="team", foreign_keys="Users.team_id", lazy="joined"
)
# Supplementary attributes
website = db.Column(db.String(128))
affiliation = db.Column(db.String(128))
country = db.Column(db.String(32))
bracket = db.Column(db.String(32))
hidden = db.Column(db.Boolean, default=False)
banned = db.Column(db.Boolean, default=False)
# Relationship for Users
captain_id = db.Column(db.Integer, db.ForeignKey("users.id", ondelete="SET NULL"))
captain = db.relationship("Users", foreign_keys=[captain_id])
field_entries = db.relationship(
"TeamFieldEntries", foreign_keys="TeamFieldEntries.team_id", lazy="joined"
)
created = db.Column(db.DateTime, default=datetime.datetime.utcnow)
def __init__(self, **kwargs):
super(Teams, self).__init__(**kwargs)
def validate_password(self, key, plaintext):
from CTFd.utils.crypto import hash_password
return hash_password(str(plaintext))
def fields(self):
return self.get_fields(admin=False)
def solves(self):
return self.get_solves(admin=False)
def fails(self):
return self.get_fails(admin=False)
def awards(self):
return self.get_awards(admin=False)
def score(self):
return self.get_score(admin=False)
def place(self):
from CTFd.utils.config.visibility import scores_visible
if scores_visible():
return self.get_place(admin=False)
else:
return None
def get_fields(self, admin=False):
if admin:
return self.field_entries
return [
entry for entry in self.field_entries if entry.field.public and entry.value
]
def get_invite_code(self):
from flask import current_app
from CTFd.utils.security.signing import serialize, hmac
secret_key = current_app.config["SECRET_KEY"]
if isinstance(secret_key, str):
secret_key = secret_key.encode("utf-8")
team_password_key = self.password.encode("utf-8")
verification_secret = secret_key + team_password_key
invite_object = {
"id": self.id,
"v": hmac(str(self.id), secret=verification_secret),
}
code = serialize(data=invite_object, secret=secret_key)
return code
def load_invite_code(cls, code):
from flask import current_app
from CTFd.utils.security.signing import (
unserialize,
hmac,
BadTimeSignature,
BadSignature,
)
from CTFd.exceptions import TeamTokenExpiredException, TeamTokenInvalidException
secret_key = current_app.config["SECRET_KEY"]
if isinstance(secret_key, str):
secret_key = secret_key.encode("utf-8")
# Unserialize the invite code
try:
# Links expire after 1 day
invite_object = unserialize(code, max_age=86400)
except BadTimeSignature:
raise TeamTokenExpiredException
except BadSignature:
raise TeamTokenInvalidException
# Load the team by the ID in the invite
team_id = invite_object["id"]
team = cls.query.filter_by(id=team_id).first_or_404()
# Create the team specific secret
team_password_key = team.password.encode("utf-8")
verification_secret = secret_key + team_password_key
# Verify the team verficiation code
verified = hmac(str(team.id), secret=verification_secret) == invite_object["v"]
if verified is False:
raise TeamTokenInvalidException
return team
def get_solves(self, admin=False):
from CTFd.utils import get_config
member_ids = [member.id for member in self.members]
solves = Solves.query.filter(Solves.user_id.in_(member_ids)).order_by(
Solves.date.asc()
)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
solves = solves.filter(Solves.date < dt)
return solves.all()
def get_fails(self, admin=False):
from CTFd.utils import get_config
member_ids = [member.id for member in self.members]
fails = Fails.query.filter(Fails.user_id.in_(member_ids)).order_by(
Fails.date.asc()
)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
fails = fails.filter(Fails.date < dt)
return fails.all()
def get_awards(self, admin=False):
from CTFd.utils import get_config
member_ids = [member.id for member in self.members]
awards = Awards.query.filter(Awards.user_id.in_(member_ids)).order_by(
Awards.date.asc()
)
freeze = get_config("freeze")
if freeze and admin is False:
dt = datetime.datetime.utcfromtimestamp(freeze)
awards = awards.filter(Awards.date < dt)
return awards.all()
def get_score(self, admin=False):
score = 0
for member in self.members:
score += member.get_score(admin=admin)
return score
def get_place(self, admin=False, numeric=False):
"""
This method is generally a clone of CTFd.scoreboard.get_standings.
The point being that models.py must be self-reliant and have little
to no imports within the CTFd application as importing from the
application itself will result in a circular import.
"""
from CTFd.utils.scores import get_team_standings
from CTFd.utils.humanize.numbers import ordinalize
standings = get_team_standings(admin=admin)
for i, team in enumerate(standings):
if team.team_id == self.id:
n = i + 1
if numeric:
return n
return ordinalize(n)
else:
return None
class Solves(Submissions):
__tablename__ = "solves"
__table_args__ = (
db.UniqueConstraint("challenge_id", "user_id"),
db.UniqueConstraint("challenge_id", "team_id"),
{},
)
id = db.Column(
None, db.ForeignKey("submissions.id", ondelete="CASCADE"), primary_key=True
)
challenge_id = column_property(
db.Column(db.Integer, db.ForeignKey("challenges.id", ondelete="CASCADE")),
Submissions.challenge_id,
)
user_id = column_property(
db.Column(db.Integer, db.ForeignKey("users.id", ondelete="CASCADE")),
Submissions.user_id,
)
team_id = column_property(
db.Column(db.Integer, db.ForeignKey("teams.id", ondelete="CASCADE")),
Submissions.team_id,
)
user = db.relationship("Users", foreign_keys="Solves.user_id", lazy="select")
team = db.relationship("Teams", foreign_keys="Solves.team_id", lazy="select")
challenge = db.relationship(
"Challenges", foreign_keys="Solves.challenge_id", lazy="select"
)
__mapper_args__ = {"polymorphic_identity": "correct"}
class Fails(Submissions):
__mapper_args__ = {"polymorphic_identity": "incorrect"}
class Tracking(db.Model):
__tablename__ = "tracking"
id = db.Column(db.Integer, primary_key=True)
type = db.Column(db.String(32))
ip = db.Column(db.String(46))
user_id = db.Column(db.Integer, db.ForeignKey("users.id", ondelete="CASCADE"))
date = db.Column(db.DateTime, default=datetime.datetime.utcnow)
user = db.relationship("Users", foreign_keys="Tracking.user_id", lazy="select")
__mapper_args__ = {"polymorphic_on": type}
def __init__(self, *args, **kwargs):
super(Tracking, self).__init__(**kwargs)
def __repr__(self):
return "<Tracking %r>" % self.ip
def get_model():
if get_config("user_mode") == USERS_MODE:
return Users
elif get_config("user_mode") == TEAMS_MODE:
return Teams
def update_check(force=False):
"""
Makes a request to ctfd.io to check if there is a new version of CTFd available. The service is provided in return
for users opting in to anonymous usage data collection. Users can opt-out of update checks by specifying
UPDATE_CHECK = False in config.py
:param force:
:return:
"""
# If UPDATE_CHECK is disabled don't check for updates at all.
if app.config.get("UPDATE_CHECK") is False:
return
# Don't do an update check if not setup
if is_setup() is False:
return
# Get when we should check for updates next.
next_update_check = get_config("next_update_check") or 0
# If we have passed our saved time or we are forcing we should check.
update = (next_update_check < time.time()) or force
if update:
try:
name = str(get_config("ctf_name")) or ""
params = {
"ctf_id": sha256(name),
"current": app.VERSION,
"python_version_raw": sys.hexversion,
"python_version": python_version(),
"db_driver": db.session.bind.dialect.name,
"challenge_count": Challenges.query.count(),
"user_mode": get_config("user_mode"),
"user_count": Users.query.count(),
"team_count": Teams.query.count(),
"theme": get_config("ctf_theme"),
"upload_provider": get_app_config("UPLOAD_PROVIDER"),
"channel": app.CHANNEL,
}
check = requests.get(
"https://versioning.ctfd.io/check", params=params, timeout=3
).json()
except requests.exceptions.RequestException:
pass
except ValueError:
pass
else:
try:
latest = check["resource"]["tag"]
html_url = check["resource"]["html_url"]
if StrictVersion(latest) > StrictVersion(app.VERSION):
set_config("version_latest", html_url)
elif StrictVersion(latest) <= StrictVersion(app.VERSION):
set_config("version_latest", None)
next_update_check_time = check["resource"].get(
"next", int(time.time() + 43200)
)
set_config("next_update_check", next_update_check_time)
except KeyError:
set_config("version_latest", None)
def statistics():
update_check()
Model = get_model()
teams_registered = Teams.query.count()
users_registered = Users.query.count()
wrong_count = (
Fails.query.join(Model, Fails.account_id == Model.id)
.filter(Model.banned == False, Model.hidden == False)
.count()
)
solve_count = (
Solves.query.join(Model, Solves.account_id == Model.id)
.filter(Model.banned == False, Model.hidden == False)
.count()
)
challenge_count = Challenges.query.count()
total_points = (
Challenges.query.with_entities(db.func.sum(Challenges.value).label("sum"))
.filter_by(state="visible")
.first()
.sum
) or 0
ip_count = Tracking.query.with_entities(Tracking.ip).distinct().count()
solves_sub = (
db.session.query(
Solves.challenge_id, db.func.count(Solves.challenge_id).label("solves_cnt")
)
.join(Model, Solves.account_id == Model.id)
.filter(Model.banned == False, Model.hidden == False)
.group_by(Solves.challenge_id)
.subquery()
)
solves = (
db.session.query(
solves_sub.columns.challenge_id,
solves_sub.columns.solves_cnt,
Challenges.name,
)
.join(Challenges, solves_sub.columns.challenge_id == Challenges.id)
.all()
)
solve_data = {}
for _chal, count, name in solves:
solve_data[name] = count
most_solved = None
least_solved = None
if len(solve_data):
most_solved = max(solve_data, key=solve_data.get)
least_solved = min(solve_data, key=solve_data.get)
db.session.close()
return render_template(
"admin/statistics.html",
user_count=users_registered,
team_count=teams_registered,
ip_count=ip_count,
wrong_count=wrong_count,
solve_count=solve_count,
challenge_count=challenge_count,
total_points=total_points,
solve_data=solve_data,
most_solved=most_solved,
least_solved=least_solved,
) | null |
158,346 | from __future__ import print_function
import os
import sys
import dataset
from sqlalchemy_utils import drop_database
from CTFd import config, create_app
from CTFd.utils import string_types
string_types = (str,)
def cast_bool(value):
if value and value.isdigit():
return int(value)
elif value and isinstance(value, string_types):
if value.lower() == "true":
return True
elif value.lower() == "false":
return False
else:
return value | null |
158,347 | from alembic import op
def upgrade():
bind = op.get_bind()
url = str(bind.engine.url)
if url.startswith("mysql"):
op.drop_constraint("awards_ibfk_1", "awards", type_="foreignkey")
op.drop_constraint("awards_ibfk_2", "awards", type_="foreignkey")
op.create_foreign_key(
"awards_ibfk_1", "awards", "teams", ["team_id"], ["id"], ondelete="CASCADE"
)
op.create_foreign_key(
"awards_ibfk_2", "awards", "users", ["user_id"], ["id"], ondelete="CASCADE"
)
op.drop_constraint("files_ibfk_1", "files", type_="foreignkey")
op.create_foreign_key(
"files_ibfk_1",
"files",
"challenges",
["challenge_id"],
["id"],
ondelete="CASCADE",
)
op.drop_constraint("flags_ibfk_1", "flags", type_="foreignkey")
op.create_foreign_key(
"flags_ibfk_1",
"flags",
"challenges",
["challenge_id"],
["id"],
ondelete="CASCADE",
)
op.drop_constraint("hints_ibfk_1", "hints", type_="foreignkey")
op.create_foreign_key(
"hints_ibfk_1",
"hints",
"challenges",
["challenge_id"],
["id"],
ondelete="CASCADE",
)
op.drop_constraint("tags_ibfk_1", "tags", type_="foreignkey")
op.create_foreign_key(
"tags_ibfk_1",
"tags",
"challenges",
["challenge_id"],
["id"],
ondelete="CASCADE",
)
op.drop_constraint("team_captain_id", "teams", type_="foreignkey")
op.create_foreign_key(
"team_captain_id",
"teams",
"users",
["captain_id"],
["id"],
ondelete="SET NULL",
)
op.drop_constraint("tracking_ibfk_1", "tracking", type_="foreignkey")
op.create_foreign_key(
"tracking_ibfk_1",
"tracking",
"users",
["user_id"],
["id"],
ondelete="CASCADE",
)
op.drop_constraint("unlocks_ibfk_1", "unlocks", type_="foreignkey")
op.drop_constraint("unlocks_ibfk_2", "unlocks", type_="foreignkey")
op.create_foreign_key(
"unlocks_ibfk_1",
"unlocks",
"teams",
["team_id"],
["id"],
ondelete="CASCADE",
)
op.create_foreign_key(
"unlocks_ibfk_2",
"unlocks",
"users",
["user_id"],
["id"],
ondelete="CASCADE",
)
elif url.startswith("postgres"):
op.drop_constraint("awards_team_id_fkey", "awards", type_="foreignkey")
op.drop_constraint("awards_user_id_fkey", "awards", type_="foreignkey")
op.create_foreign_key(
"awards_team_id_fkey",
"awards",
"teams",
["team_id"],
["id"],
ondelete="CASCADE",
)
op.create_foreign_key(
"awards_user_id_fkey",
"awards",
"users",
["user_id"],
["id"],
ondelete="CASCADE",
)
op.drop_constraint("files_challenge_id_fkey", "files", type_="foreignkey")
op.create_foreign_key(
"files_challenge_id_fkey",
"files",
"challenges",
["challenge_id"],
["id"],
ondelete="CASCADE",
)
op.drop_constraint("flags_challenge_id_fkey", "flags", type_="foreignkey")
op.create_foreign_key(
"flags_challenge_id_fkey",
"flags",
"challenges",
["challenge_id"],
["id"],
ondelete="CASCADE",
)
op.drop_constraint("hints_challenge_id_fkey", "hints", type_="foreignkey")
op.create_foreign_key(
"hints_challenge_id_fkey",
"hints",
"challenges",
["challenge_id"],
["id"],
ondelete="CASCADE",
)
op.drop_constraint("tags_challenge_id_fkey", "tags", type_="foreignkey")
op.create_foreign_key(
"tags_challenge_id_fkey",
"tags",
"challenges",
["challenge_id"],
["id"],
ondelete="CASCADE",
)
op.drop_constraint("team_captain_id", "teams", type_="foreignkey")
op.create_foreign_key(
"team_captain_id",
"teams",
"users",
["captain_id"],
["id"],
ondelete="SET NULL",
)
op.drop_constraint("tracking_user_id_fkey", "tracking", type_="foreignkey")
op.create_foreign_key(
"tracking_user_id_fkey",
"tracking",
"users",
["user_id"],
["id"],
ondelete="CASCADE",
)
op.drop_constraint("unlocks_team_id_fkey", "unlocks", type_="foreignkey")
op.drop_constraint("unlocks_user_id_fkey", "unlocks", type_="foreignkey")
op.create_foreign_key(
"unlocks_team_id_fkey",
"unlocks",
"teams",
["team_id"],
["id"],
ondelete="CASCADE",
)
op.create_foreign_key(
"unlocks_user_id_fkey",
"unlocks",
"users",
["user_id"],
["id"],
ondelete="CASCADE",
) | null |
158,348 | from alembic import op
def downgrade():
bind = op.get_bind()
url = str(bind.engine.url)
if url.startswith("mysql"):
op.drop_constraint("unlocks_ibfk_1", "unlocks", type_="foreignkey")
op.drop_constraint("unlocks_ibfk_2", "unlocks", type_="foreignkey")
op.create_foreign_key("unlocks_ibfk_1", "unlocks", "teams", ["team_id"], ["id"])
op.create_foreign_key("unlocks_ibfk_2", "unlocks", "users", ["user_id"], ["id"])
op.drop_constraint("tracking_ibfk_1", "tracking", type_="foreignkey")
op.create_foreign_key(
"tracking_ibfk_1", "tracking", "users", ["user_id"], ["id"]
)
op.drop_constraint("team_captain_id", "teams", type_="foreignkey")
op.create_foreign_key(
"team_captain_id", "teams", "users", ["captain_id"], ["id"]
)
op.drop_constraint("tags_ibfk_1", "tags", type_="foreignkey")
op.create_foreign_key(
"tags_ibfk_1", "tags", "challenges", ["challenge_id"], ["id"]
)
op.drop_constraint("hints_ibfk_1", "hints", type_="foreignkey")
op.create_foreign_key(
"hints_ibfk_1", "hints", "challenges", ["challenge_id"], ["id"]
)
op.drop_constraint("flags_ibfk_1", "flags", type_="foreignkey")
op.create_foreign_key(
"flags_ibfk_1", "flags", "challenges", ["challenge_id"], ["id"]
)
op.drop_constraint("files_ibfk_1", "files", type_="foreignkey")
op.create_foreign_key(
"files_ibfk_1", "files", "challenges", ["challenge_id"], ["id"]
)
op.drop_constraint("awards_ibfk_1", "awards", type_="foreignkey")
op.drop_constraint("awards_ibfk_2", "awards", type_="foreignkey")
op.create_foreign_key("awards_ibfk_1", "awards", "teams", ["team_id"], ["id"])
op.create_foreign_key("awards_ibfk_2", "awards", "users", ["user_id"], ["id"])
elif url.startswith("postgres"):
op.drop_constraint("unlocks_team_id_fkey", "unlocks", type_="foreignkey")
op.drop_constraint("unlocks_user_id_fkey", "unlocks", type_="foreignkey")
op.create_foreign_key(
"unlocks_team_id_fkey", "unlocks", "teams", ["team_id"], ["id"]
)
op.create_foreign_key(
"unlocks_user_id_fkey", "unlocks", "users", ["user_id"], ["id"]
)
op.drop_constraint("tracking_user_id_fkey", "tracking", type_="foreignkey")
op.create_foreign_key(
"tracking_user_id_fkey", "tracking", "users", ["user_id"], ["id"]
)
op.drop_constraint("team_captain_id", "teams", type_="foreignkey")
op.create_foreign_key(
"team_captain_id", "teams", "users", ["captain_id"], ["id"]
)
op.drop_constraint("tags_challenge_id_fkey", "tags", type_="foreignkey")
op.create_foreign_key(
"tags_challenge_id_fkey", "tags", "challenges", ["challenge_id"], ["id"]
)
op.drop_constraint("hints_challenge_id_fkey", "hints", type_="foreignkey")
op.create_foreign_key(
"hints_challenge_id_fkey", "hints", "challenges", ["challenge_id"], ["id"]
)
op.drop_constraint("flags_challenge_id_fkey", "flags", type_="foreignkey")
op.create_foreign_key(
"flags_challenge_id_fkey", "flags", "challenges", ["challenge_id"], ["id"]
)
op.drop_constraint("files_challenge_id_fkey", "files", type_="foreignkey")
op.create_foreign_key(
"files_challenge_id_fkey", "files", "challenges", ["challenge_id"], ["id"]
)
op.drop_constraint("awards_team_id_fkey", "awards", type_="foreignkey")
op.drop_constraint("awards_user_id_fkey", "awards", type_="foreignkey")
op.create_foreign_key(
"awards_team_id_fkey", "awards", "teams", ["team_id"], ["id"]
)
op.create_foreign_key(
"awards_user_id_fkey", "awards", "users", ["user_id"], ["id"]
) | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.