Example #1
0
class MedicalConditions(db.Entity):
    mc_id = orm.PrimaryKey(int, auto=True)
    name = orm.Required(str)
    radiologyAssesment = orm.Set("RadiologyAssesment", reverse="result")
    social_history = orm.Set(SocialHistory, reverse="condition")
    family_history = orm.Set(FamilyMedicalHistory, reverse="condition")
    radiologyAssesmentHistory = orm.Set(RadiologyAssesmentHistory,
                                        reverse="result")
Example #2
0
class Resource(db.Entity):
    """ Represents a resource node. An initial resource can only be modified
  from the configuration file. At startup, all initial resources are deleted
  and their associated permissions are flushed. """

    id = orm.PrimaryKey(str)
    initial = orm.Required(bool, default=False)
    permissions = orm.Set('Permission')
Example #3
0
class Logopic(db.Entity):
    """ Модель картинки в шапке сайта """

    picture = orm.Required(str, 255)
    sha256sum = orm.Required(str, 64)
    visible = orm.Required(bool, default=True)
    description = orm.Optional(orm.LongStr)
    original_link = orm.Optional(str, 255)
    original_link_label = orm.Optional(orm.LongStr, lazy=False)
    created_at = orm.Required(datetime, 6, default=datetime.utcnow)
    updated_at = orm.Required(datetime, 6, default=datetime.utcnow)

    bl = Resource('bl.logopic')

    @property
    def url(self):
        return url_for('media', filename=self.picture, v=self.sha256sum[:6])
class User(DB.Entity):
    email = orm.PrimaryKey(str)
    password_hash = orm.Required(bytes)
    groups = orm.Required(str, default="user")

    @staticmethod
    def create(**kwargs):
        return User(**kwargs)

    def dictify(self):
        return {
            'email': self.email,
            'groups': self.group(),
        }

    def group(self):
        return ['anybody'] + self.groups.split()
Example #5
0
class Subscription(db.Entity):
    """Модель с информацией о подписке на уведомления.

    Куда указывает target_id:
    - author_story: Author
    - story_chapter: Story
    - story_comment: Story
    - story_lcomment: Story
    - news_comment: NewsItem
    """
    user = orm.Required(Author)
    type = orm.Required(str, 24, index=True)
    target_id = orm.Optional(int)
    to_email = orm.Required(bool, default=True)
    to_tracker = orm.Required(bool, default=True)

    orm.composite_index(type, target_id)
Example #6
0
class Guild(cogs.__shared.db.Entity):
    """Guild states and comments"""
    _table_ = table_prefix + 'guilds'

    guild_id = orm.PrimaryKey(str, 20)  # Discord guild ID
    state = orm.Required(int, size=8, unsigned=True)  # Event state
    comment = orm.Optional(str, 4000, lazy=True)  # Event comment
    wishes_gifts = orm.Set('WishGift')
Example #7
0
class User(db.Entity):
    """ Represents a user. An initial user can only be modified from the
  configuration file. At startup, all initial users are re-set. """

    username = orm.PrimaryKey(str)
    password_hash = orm.Required(str)
    initial = orm.Required(bool, default=False)
    permissions = orm.Set('Permission')
    tokens = orm.Set('Token')

    def __init__(self, **kwargs):
        password = kwargs.pop('password', None)
        if password is not None:
            kwargs['password_hash'] = 'foo32'
        super().__init__(**kwargs)
        if password is not None:
            self.set_password(password)

    @staticmethod
    def _hash_password(password: str) -> str:
        password += 'ThisIsMySalt(*'  # TODO (@NiklasRosenstein)
        return hashlib.sha256(password.encode('utf8')).hexdigest()

    def set_password(self, password: str) -> None:
        self.password_hash = self._hash_password(password)

    def check_password(self, password: str) -> bool:
        return self._hash_password(password) == self.password_hash

    @classmethod
    def get_for_token(cls, token_str: str) -> 'Token':
        token = Token.get(value=token_str)
        if token and token.expires_at < datetime.utcnow():
            token.delete()
            return None
        return token.user if token else None

    def create_token(self) -> 'Token':
        return Token(user=self)

    def check_permission(self, resource: Union[str, 'Resource'],
                         perm: str) -> bool:
        if isinstance(resource, str):
            resource = Resource[resource]
        return Permission.get(name=perm, user=self,
                              resource=resource) is not None
Example #8
0
class Subreddit(db.Entity):
    """
    Subreddit - Entity for a single subreddit
    """
    id = orm.PrimaryKey(int)
    name = orm.Required(str, unique=True)
    titles = orm.Set("Titles")
    nsfw_percentage = orm.Optional(float)
Example #9
0
    class TorrentState(db.Entity):
        """
        This ORM class represents torrent swarms. It is used by HealthChecker.
        """

        rowid = orm.PrimaryKey(int, auto=True)
        infohash = orm.Required(bytes, unique=True)
        seeders = orm.Optional(int, default=0)
        leechers = orm.Optional(int, default=0)
        last_check = orm.Optional(int, size=64, default=0)
        self_checked = orm.Optional(bool, default=False, sql_default='0')
        has_data = orm.Required(bool,
                                default=False,
                                sql_default='0',
                                volatile=True)
        metadata = orm.Set('TorrentMetadata', reverse='health')
        trackers = orm.Set('TrackerState', reverse='torrents')
class World(db.Entity):
    _table_ = "world"
    id = orm.PrimaryKey(int)
    randomNumber = orm.Required(int, column="randomnumber")

    def to_dict(self):
        """Return object data in easily serializeable format"""
        return {"id": self.id, "randomNumber": self.randomNumber}
Example #11
0
class HtmlBlock(db.Entity):
    name = orm.Required(str, 64)
    lang = orm.Required(str, 6, default='none')
    content = orm.Optional(orm.LongStr, autostrip=False)
    is_template = orm.Required(bool, default=False)
    date = orm.Required(datetime, 6, default=datetime.utcnow)
    updated = orm.Required(datetime, 6, default=datetime.utcnow)

    orm.PrimaryKey(name, lang)

    bl = Resource('bl.htmlblock')

    def __str__(self):
        return self.name

    def before_update(self):
        self.updated = datetime.utcnow()
class Tokens(db.Entity):
    _table_ = ('public', 'Tokens')
    TokenID = orm.PrimaryKey(int, auto=True)
    Token = orm.Required(str, unique=True)
    ClientIP = orm.Required(str)
    UserID = orm.Required("Users", reverse="UserToken")
    GenerationDate = orm.Required(datetime)
    AuthorizationRequestToken = orm.Set("AuthorizationRequests",
                                        reverse="TokenID")
    FinantionalRequestToken = orm.Set("FinantionalRequests", reverse="TokenID")
    ReversalRequestToken = orm.Set("ReversalRequests", reverse="TokenID")
    SettlementRequestToken = orm.Set("SettlementRequests", reverse="TokenID")
    AdministrativeRequestToken = orm.Set("AdministrativeRequests",
                                         reverse="TokenID")
    NetworkManagementRequestToken = orm.Set("NetworkManagementRequests",
                                            reverse="TokenID")
    KeyExchangeRequestToken = orm.Set("KeyExchangeRequests", reverse="TokenID")
Example #13
0
class Account(db.Entity):
    name = orm.PrimaryKey(str)
    salt_str = orm.Required(str)
    verifier_str = orm.Required(str)
    session_key_str = orm.Optional(str)

    # Characters on this account.
    characters = orm.Set('Player')

    @property
    def salt(self) -> int:
        return int(self.salt_str)

    @property
    def verifier(self) -> int:
        return int(self.verifier_str)

    @property
    def session_key(self) -> int:
        return int(self.session_key_str)

    @classmethod
    def New(cls, username: Text, password: Text) -> 'Account':
        """Create a new Account and return it.

        This must be done inside a PonyORM session.

        Args:
            username: The username of the account.
            password: The password of the account.

        Returns:
            The newly created account.
        """
        salt = srp.Random(32)
        verifier = srp.GenerateVerifier(
            username.upper(),
            password.upper(),
            salt,
        )

        return Account(
            name=username.upper(),
            salt_str=str(salt),
            verifier_str=str(verifier),
        )
Example #14
0
class ToolProjectCategory(db.Entity):
    """
    Represents the category of a project as represented by the associated tools.  Not all tools organize projects
    into categories
    """
    id = orm.PrimaryKey(int, auto=True)
    tool_category_name = orm.Required(str)
    workflows = orm.Set('Workflow', reverse="categories")
Example #15
0
 class TorrentState(db.Entity):
     rowid = orm.PrimaryKey(int, auto=True)
     infohash = orm.Required(database_blob, unique=True)
     seeders = orm.Optional(int, default=0)
     leechers = orm.Optional(int, default=0)
     last_check = orm.Optional(int, size=64, default=0)
     metadata = orm.Set('TorrentMetadata', reverse='health')
     trackers = orm.Set('TrackerState', reverse='torrents')
Example #16
0
class AdminLog(db.Entity):
    """Лог изменений в админке"""
    # ported from django

    ADDITION = 1
    CHANGE = 2
    DELETION = 3

    action_time = orm.Required(datetime, 6, default=datetime.utcnow)
    user = orm.Optional(Author)
    type = orm.Required(AdminLogType)
    object_id = orm.Required(str, 255)  # str for non-integer pk
    object_repr = orm.Optional(str, 255, autostrip=False)
    action_flag = orm.Required(int, size=8)
    change_message = orm.Optional(orm.LongStr)

    bl = Resource('bl.adminlog')
Example #17
0
class Audiofile(db.Entity):

    id = orm.PrimaryKey(str)
    name = orm.Required(str)
    filename = orm.Required(str, unique=True)
    duration = orm.Required(float)
    filesize = orm.Required(float)

    playlists = orm.Set(lambda: Playlist)

    def before_delete(self):
        filename = Path(self.filename)
        if filename.exists():
            filename.unlink()

    def __repr__(self):
        return f'Audio file {self.name}'
Example #18
0
class Category(db.Entity):
    """ Metadata for a category """

    category = orm.Optional(str)
    file_path = orm.Required(str)
    sort_name = orm.Optional(str)

    aliases = orm.Set("PathAlias")
Example #19
0
class Assignment(db.Entity):
    due_date = orm.Required(date)
    word_limit = orm.Optional(int)
    submissions = orm.Set('Submission')
    description = orm.Required(str)
    isopen = orm.Required(bool, default=True)
    nimages = orm.Required(int, default=0)

    def as_dict(self):
        return {
            'id': self.id,
            'isopen': self.isopen,
            'word_limit': self.word_limit,
            'due_date': self.due_date,
            'description': self.description,
            'nimages': self.nimages
        }
Example #20
0
class Genre(db.Entity):
    _table_ = 'genres'

    id = orm.PrimaryKey(int, auto=True)

    name = orm.Required(str)

    books = orm.Set("Book")
Example #21
0
class Izlazak(db.Entity):
    id = orm.PrimaryKey(int, auto=True)
    kategorija = orm.Required(str)
    destinacija = orm.Required(str)
    adresa = orm.Required(str)
    broj = orm.Required(int)
    email = orm.Required(str)
    opis = orm.Required(str)
    poster = orm.Required(str)
    slika = orm.Required(str)
Example #22
0
class Resource(db1.Entity):
    _table_ = 'Resources'
    currency = orm.Required('Currency')
    algorythm = orm.Required(str)
    gpu = orm.Required(str)
    rew24 = orm.Required(float)
    rewbtc24 = orm.Required(float)
    rewusd24 = orm.Required(float)
    energy = orm.Required(float)
    dt = orm.Required(date)
Example #23
0
class Filmovi(db.Entity):
    id = orm.PrimaryKey(int, auto=True)
    naziv_kategorije = orm.Required(str)
    originalni_naziv = orm.Required(str)
    godina_izdavanja = orm.Required(int)
    redatelj = orm.Required(str)
    opis = orm.Required(str)
    trailer = orm.Required(str)
    poster = orm.Required(str)
    slika = orm.Required(str)
Example #24
0
class Direction(db.Entity):
    _table_ = 'Directions'
    departure = orm.Required(Airport, reverse='departures')
    destination = orm.Required(Airport, reverse='directions')
    cost = orm.Required(int)
    currency = orm.Required(str)
    duration = orm.Required(int)
    distance = orm.Required(int)
    iteration = orm.Required(int)
    dt = orm.Required(datetime)
class WebResource(BaseEntityClass, database.Entity):
    _table_ = MYSQL_WEB_RESOURCES_TABLE_NAME
    id = pny.PrimaryKey(str, auto=False)
    providerId = pny.Required(int)
    title = pny.Optional(str)
    domain = pny.Optional(str)
    logo = pny.Optional(str)
    hook = pny.Optional(str, lazy=True)
    date_created = pny.Required(datetime.datetime,
                                default=lambda: datetime.datetime.now(),
                                lazy=True)
    date_modified = pny.Required(datetime.datetime,
                                 default=lambda: datetime.datetime.now(),
                                 auto=True,
                                 lazy=True)

    @staticmethod
    @inherit_docstring_from(BaseEntityClass)
    def get_table_name():
        return MYSQL_WEB_RESOURCES_TABLE_NAME

    @staticmethod
    @inherit_docstring_from(BaseEntityClass)
    def get_unique_search_attribute():
        return 'id'

    @staticmethod
    @inherit_docstring_from(BaseEntityClass)
    def create_record(**kwargs):
        WebResource(**kwargs)

    @staticmethod
    @inherit_docstring_from(BaseEntityClass)
    def update_record(record_id, **kwargs):
        search_query = {WebResource.get_unique_search_attribute(): record_id}
        web_resource = WebResource.get(**search_query)
        if web_resource is not None:
            for key, value in kwargs.iteritems():
                if not hasattr(web_resource, key):
                    continue
                setattr(web_resource, key, value)

    @inherit_docstring_from(BaseEntityClass)
    def get_redis_key(self):
        return REDIS_WEB_RESOURCE_KEY
Example #26
0
class Post(db.Entity):
    _table_ = "posts"
    title = orm.Required(orm.unicode, 100, nullable=False, unique=True)
    slug = orm.Required(orm.unicode, 100, nullable=False, unique=True)

    # Modification dates etc
    created = orm.Required(datetime.date, nullable=False)
    posted = orm.Optional(datetime.datetime, nullable=True)
    modified = orm.Required(datetime.datetime, nullable=True)

    content = orm.Required(orm.unicode, nullable=False)

    header_image = orm.Optional(orm.unicode, nullable=True)
    header_caption = orm.Optional(orm.unicode, nullable=True)

    # Special Page posts
    is_special_page = orm.Required(bool, sql_default=False)

    tags = orm.Set("Tag")

    draft = orm.Required(bool, nullable=False)

    def __repr__(self):
        return "<Post {0}>".format(self.title)

    def created_ago(self):
        return self.created - datetime.date.today()

    def url(self):
        if self.is_special_page:
            return url_for("view_static_page", slug=self.slug)
        return url_for("view_post", slug=self.slug)

    def clear_cache(self):
        cache.delete("post_{0}".format(self.id))

    def rendered_content(self):
        key = "post_{0}".format(self.id)
        hit = cache.get(key)
        if hit:
            return hit

        content = md.convert(self.content)
        cache.set(key, content)
        return content

    def is_local_header_image(self):
        uri = parse.urlparse(self.header_image)
        return not bool(uri.netloc)

    def download_header_image(self):
        req = requests.get(self.header_image, stream=True)
        storage = FileStorage(
            stream=iter_to_stream(req.iter_content(chunk_size=10)))

        key = str(b32encode(urandom(15)), "utf8")
        ext = mimetypes.guess_extension(req.headers["content-type"])
        name = key + ext
        storage.save(os.path.join(app.config["UPLOAD_FOLDER"], name))
        self.header_image = url_for('uploads', filename=name)
Example #27
0
class Zeremonien(db.Entity):
    url = orm.PrimaryKey(str)
    Titel = orm.Required(str)
    Probe = orm.Required(str)
    Wirkung = orm.Required(str)
    Zeremoniedauer = orm.Required(str)
    KaP_Kosten = orm.Required(str)
    Reichweite = orm.Required(str)
    Wirkungsdauer = orm.Required(str)
    Zielkategorie = orm.Required(str)
    Verbreitung = orm.Required(str)
    Steigerungsfaktor = orm.Optional(str)
    Liturgieerweiterungen = orm.Optional(orm.StrArray)
    Publikation = orm.Optional(str)
Example #28
0
class PDF(db.Entity):
    address = orm.PrimaryKey(str)
    tags = orm.Set(Tag)
    subjects = orm.Set(Tag)
    is_eng = orm.Required(bool)

    def remove(self):
        with orm.db_session:
            PDF[self.address].delete()
Example #29
0
 class User(db.Entity):
     username = orm.Optional(str, unique=True)
     password_hash = orm.Optional(str)
     email = orm.Required(str, unique=True)
     dt_registered = orm.Optional(datetime.datetime)
     dt_last_visit = orm.Optional(datetime.datetime)
     verified = orm.Optional(bool)
     failed_login = orm.Optional(int)
     last_failed_login = orm.Optional(datetime.datetime)
Example #30
0
class Tag(db.Entity):
    _table_ = 'Tags'

    name = orm.Required(unicode, unique=True)
    todos = orm.Set("Todo")

    @property
    def url(self):
        return "http://localhost:5000/tags/{}".format(self.id)