Giter Site home page Giter Site logo

xnuinside / py-models-parser Goto Github PK

View Code? Open in Web Editor NEW
16.0 5.0 2.0 134 KB

Parser for Different Python Models (pure Python classes, Pydantic, Enums, ORMs: DjangoORM, Tortoise, SqlAlchemy, GinoORM, PonyORM, Pydal) to extract information about columns(attrs), model, table args,etc in one format.

License: MIT License

Shell 0.35% Python 99.65%
pydantic parser python models orm tortoise-orm sqlalchemy gino-orm dataclasses django-orm

py-models-parser's Introduction

Py-Models-Parser

badge1 badge2 badge3 workflow

It's as second Parser that done by me, first is a https://github.com/xnuinside/simple-ddl-parser for SQL DDL with different dialects.

Py-Models-Parser can parse & extract information from models & table definitions:

Number of supported models will be increased, check 'TODO' section, if you want to have support of different models types - please open the issue.

Py-Models-Parser written with PEG parser and it's python implementation - parsimonious. It's pretty new and I did not cover all possible test cases, so if you will have an issue - please just open an issue in this case with example, I will fix it as soon as possible.

Py-Models-Parser take as input different Python code with Models and provide output in standard form:

    [
        'name': 'ModelName',
        'parents': ['BaseModel'], # class parents that defined in (), for example: `class MaterialType(str, Enum):` parents - str, Enum
        'attrs':
    {
        'type': 'integer',
        'name': 'attr_name',
        'default': 'default_value',
        'properties': {
            ...
        }
    },
    'properties': {
        'table_name': ...
    }
    ]

For ORM models 'attrs' contains Columns of course.

3 keys - 'type', 'name', 'default' exists in parse result 'attrs' of all Models 'properties' key contains additional information for attribut or column depend on Model type, for example, in ORM models it can contains 'foreign_key' key if this column used ForeignKey, or 'server_default' if it is a SqlAlchemy model or GinoORM.

Model level 'properties' contains information relative to model, for example, if it ORM model - table_name

NOTE: it's is a text parser, so it don't import or load your code, parser work with source code as text, not objects in Python. So to run parser you DO NOT NEED install dependencies for models, that you tries to parse - only models.

How to install

    pip install py-models-parser

How to use

Library detect automaticaly that type of models you tries to parse. You can check a lot of examples in test/ folder on the GitHub

  1. You can parse models from python string:
from py_models_parser import parse

models_str =  """from gino import Gino

db = Gino()


class OrderItems(db.Model):

    __tablename__ = 'order_items'

    product_no = db.Column(db.Integer(), db.ForeignKey('products.product_no'), ondelete="RESTRICT", primary_key=True)
    order_id = db.Column(db.Integer(), db.ForeignKey('orders.order_id'), ondelete="CASCADE", primary_key=True)
    type = db.Column(db.Integer(), db.ForeignKey('types.type_id'), ondelete="RESTRICT", onupdate="CASCADE")
    
    """
result = parse(models_str)
  1. Parse models from file:
    from py_models_parser import parse_from_file


    file_path = "path/to/your/models.py"
    # for example: tests/data/dataclass_defaults.py
    result = parse_from_file(file_path)
  1. Parse models from file with command line
    pmp path_to_models.py 

    # for example: pmp tests/data/dataclass_defaults.py

Output from cli can be dumped in 'output_models.json' file - use flag '-d' '--dump' if you want to change target file name, provide it after argument like '-d target_file.json'

    # example how to dump output from cli

    pmp path_to_models.py -d target_file.json

Output example

You can find a lot of output examples in tests - https://github.com/xnuinside/py-models-parser/tree/main/tests

For model from point 1 (above) library will produce the result:

    [
        {
            "attrs": [
                {
                    "default": None,
                    "name": "product_no",
                    "properties": {
                        "foreign_key": "'products.product_no'",
                        "ondelete": '"RESTRICT"',
                        "primary_key": "True",
                    },
                    "type": "db.Integer()",
                },
                {
                    "default": None,
                    "name": "order_id",
                    "properties": {
                        "foreign_key": "'orders.order_id'",
                        "ondelete": '"CASCADE"',
                        "primary_key": "True",
                    },
                    "type": "db.Integer()",
                },
                {
                    "default": None,
                    "name": "type",
                    "properties": {
                        "foreign_key": "'types.type_id'",
                        "ondelete": '"RESTRICT"',
                        "onupdate": '"CASCADE"',
                    },
                    "type": "db.Integer()",
                },
            ],
            "name": "OrderItems",
            "parents": ["db.Model"],
            "properties": {"table_name": "'order_items'"},
        }
    ]

TODO: in next Release

  1. Add more tests for supported models
  2. Add support for SQLAlchemy Core Tables

Changelog

v0.7.0 Updates:

  1. Added support for latest version of parsimonious. Library now works with Python 3.11.

v0.6.0 Features:

  1. Added support for Encode ORM models https://github.com/encode/orm
  2. Added support for Piccolo ORM models https://piccolo-orm.readthedocs.io/en/latest/piccolo/schema/defining.html

v0.5.1 Fixes:

  1. Sometimes multiple parents names in "parents" output was joined in one string - fixed.

v0.5.0

  1. Added base support for Pydal tables definitions
  2. Added support for python list syntax like []

v0.4.0

  1. return tuples (multiple values) is parsed correctly now
  2. symbols like *&^%$#!±~§<>` now does not cause any errors
  3. classes without any args does not cause an error anymore

v0.3.0

  1. Added cli - pmp command with args -d, --dump
  2. Added support for simple Django ORM models
  3. Added base support for pure Python Classes

v0.2.0

  1. Added support for Dataclasses
  2. Added parse_from_file method
  3. Added correct work with types with comma inside, like: Union[dict, list] or Union[dict, list, tuple, anything]

v0.1.1

  1. Added base parser logic & tests for Pydantic, Enums, SQLAlchemy Models, GinoORM models, TortoiseORM models

py-models-parser's People

Contributors

xnuinside avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

py-models-parser's Issues

Make Parser and Convert Models from OAS3 (open api specification 3 / swagger) to Python Models

Is your feature request related to a problem? Please describe.

Today it is possible from OAS3/Swagger to make a model for Fask or FastAPi (https://openapi-generator.tech/docs/generators/python-flask), but it is super complicated use this program, first of all, that built in Java, second of all this program do not create a ORM schema.

So, today I make a script in Python to convert OAS3 Schema to SQL DDL and use your packages to create ORM schema the way I can create a FastAPI from a OAS3 and a SQLAlchemy ORM altomatically.

But it is easier to create directly with omymodel or py-models-parser in a unique shot.

Describe the solution you'd like
My proposal is a way to parse models from OAS3/Swagger to Python model

Describe alternatives you've considered
It is possible convert OAS3 in SQL Schema. Today I did not use Simple-SQL-Parse dictonary schema, but I would use this structure to make easier conversion.

required parsimonious doesn't run on python 3.11

Describe the bug

  File "/home/hrehfeld/projects/ext/omymodels/.venv/lib/python3.11/site-packages/py_models_parser/__init__.py", line 1, in <module>
    from py_models_parser.core import dump_result, parse, parse_from_file
  File "/home/hrehfeld/projects/ext/omymodels/.venv/lib/python3.11/site-packages/py_models_parser/core.py", line 5, in <module>
    from py_models_parser.grammar import grammar
  File "/home/hrehfeld/projects/ext/omymodels/.venv/lib/python3.11/site-packages/py_models_parser/grammar.py", line 1, in <module>
    from parsimonious.grammar import Grammar
  File "/home/hrehfeld/projects/ext/omymodels/.venv/lib/python3.11/site-packages/parsimonious/__init__.py", line 9, in <module>
    from parsimonious.grammar import Grammar, TokenGrammar
  File "/home/hrehfeld/projects/ext/omymodels/.venv/lib/python3.11/site-packages/parsimonious/grammar.py", line 14, in <module>
    from parsimonious.expressions import (Literal, Regex, Sequence, OneOf,
  File "/home/hrehfeld/projects/ext/omymodels/.venv/lib/python3.11/site-packages/parsimonious/expressions.py", line 9, in <module>
    from inspect import getargspec
ImportError: cannot import name 'getargspec' from 'inspect' (/usr/lib/python3.11/inspect.py)

To Reproduce
just install on py 3.11

Desktop (please complete the following information):

  • OS: archlinux

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.