Skip to content

Commit 2e5ab26

Browse files
committed
working on sqlalchemy examples to make them better
1 parent d906a94 commit 2e5ab26

File tree

92 files changed

+6899
-2288
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

92 files changed

+6899
-2288
lines changed

content/pages/examples/flask/flask-blueprints-blueprint.markdown

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -488,6 +488,61 @@ def generate_csrf(secret_key=None, token_key=None):
488488
if field_name not in g:
489489

490490

491+
## ... source file abbreviated to get to Blueprint examples ...
492+
493+
494+
return None
495+
496+
def protect(self):
497+
if request.method not in current_app.config['WTF_CSRF_METHODS']:
498+
return
499+
500+
try:
501+
validate_csrf(self._get_csrf_token())
502+
except ValidationError as e:
503+
logger.info(e.args[0])
504+
self._error_response(e.args[0])
505+
506+
if request.is_secure and current_app.config['WTF_CSRF_SSL_STRICT']:
507+
if not request.referrer:
508+
self._error_response('The referrer header is missing.')
509+
510+
good_referrer = 'https://{0}/'.format(request.host)
511+
512+
if not same_origin(request.referrer, good_referrer):
513+
self._error_response('The referrer does not match the host.')
514+
515+
g.csrf_valid = True # mark this request as CSRF valid
516+
517+
def exempt(self, view):
518+
519+
~~ if isinstance(view, Blueprint):
520+
self._exempt_blueprints.add(view.name)
521+
return view
522+
523+
if isinstance(view, string_types):
524+
view_location = view
525+
else:
526+
view_location = '.'.join((view.__module__, view.__name__))
527+
528+
self._exempt_views.add(view_location)
529+
return view
530+
531+
def _error_response(self, reason):
532+
raise CSRFError(reason)
533+
534+
def error_handler(self, view):
535+
536+
warnings.warn(FlaskWTFDeprecationWarning(
537+
'"@csrf.error_handler" is deprecated. Use the standard Flask '
538+
'error system with "@app.errorhandler(CSRFError)" instead. This '
539+
'will be removed in 1.0.'
540+
), stacklevel=2)
541+
542+
@wraps(view)
543+
def handler(reason):
544+
545+
491546
## ... source file continues with no further Blueprint examples...
492547

493548
```

content/pages/examples/flask/flask-sessions-badsignature.markdown

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,92 @@ class Role(db.Model):
120120
'Administrator': (
121121

122122

123+
## ... source file abbreviated to get to BadSignature examples ...
124+
125+
126+
127+
@password.setter
128+
def password(self, password):
129+
self.password_hash = generate_password_hash(password)
130+
131+
def verify_password(self, password):
132+
return check_password_hash(self.password_hash, password)
133+
134+
def generate_confirmation_token(self, expiration=604800):
135+
136+
s = Serializer(current_app.config['SECRET_KEY'], expiration)
137+
return s.dumps({'confirm': self.id})
138+
139+
def generate_email_change_token(self, new_email, expiration=3600):
140+
s = Serializer(current_app.config['SECRET_KEY'], expiration)
141+
return s.dumps({'change_email': self.id, 'new_email': new_email})
142+
143+
def generate_password_reset_token(self, expiration=3600):
144+
s = Serializer(current_app.config['SECRET_KEY'], expiration)
145+
return s.dumps({'reset': self.id})
146+
147+
def confirm_account(self, token):
148+
s = Serializer(current_app.config['SECRET_KEY'])
149+
try:
150+
data = s.loads(token)
151+
~~ except (BadSignature, SignatureExpired):
152+
return False
153+
if data.get('confirm') != self.id:
154+
return False
155+
self.confirmed = True
156+
db.session.add(self)
157+
db.session.commit()
158+
return True
159+
160+
def change_email(self, token):
161+
s = Serializer(current_app.config['SECRET_KEY'])
162+
try:
163+
data = s.loads(token)
164+
~~ except (BadSignature, SignatureExpired):
165+
return False
166+
if data.get('change_email') != self.id:
167+
return False
168+
new_email = data.get('new_email')
169+
if new_email is None:
170+
return False
171+
if self.query.filter_by(email=new_email).first() is not None:
172+
return False
173+
self.email = new_email
174+
db.session.add(self)
175+
db.session.commit()
176+
return True
177+
178+
def reset_password(self, token, new_password):
179+
s = Serializer(current_app.config['SECRET_KEY'])
180+
try:
181+
data = s.loads(token)
182+
~~ except (BadSignature, SignatureExpired):
183+
return False
184+
if data.get('reset') != self.id:
185+
return False
186+
self.password = new_password
187+
db.session.add(self)
188+
db.session.commit()
189+
return True
190+
191+
@staticmethod
192+
def generate_fake(count=100, **kwargs):
193+
from sqlalchemy.exc import IntegrityError
194+
from random import seed, choice
195+
from faker import Faker
196+
197+
fake = Faker()
198+
roles = Role.query.all()
199+
200+
seed()
201+
for i in range(count):
202+
u = User(
203+
first_name=fake.first_name(),
204+
last_name=fake.last_name(),
205+
email=fake.email(),
206+
password='password',
207+
208+
123209
## ... source file continues with no further BadSignature examples...
124210

125211
```
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
title: sqlalchemy.dialects mssql code examples
2+
category: page
3+
slug: sqlalchemy-dialects-mssql-examples
4+
sortorder: 500031000
5+
toc: False
6+
sidebartitle: sqlalchemy.dialects mssql
7+
meta: Python example code for the mssql function from the sqlalchemy.dialects module of the SQLAlchemy project.
8+
9+
10+
mssql is a function within the sqlalchemy.dialects module of the SQLAlchemy project.
11+
12+
13+
## Example 1 from marshmallow-sqlalchemy
14+
[marshmallow-sqlalchemy](https://github.com/marshmallow-code/marshmallow-sqlalchemy)
15+
([project documentation](https://marshmallow-sqlalchemy.readthedocs.io/en/latest/))
16+
is a code library that makes it easier to use
17+
[SQLAlchemy](/sqlalchemy.html) with the
18+
[Marshmallow](https://marshmallow.readthedocs.io/en/stable/)
19+
data serialization tool.
20+
21+
The marshmallow-sqlalchemy project is provided as open source under the
22+
[MIT license](https://github.com/marshmallow-code/marshmallow-sqlalchemy/blob/dev/LICENSE).
23+
24+
[**marshmallow-sqlalchemy / src/marshmallow_sqlalchemy / convert.py**](https://github.com/marshmallow-code/marshmallow-sqlalchemy/blob/dev/src/marshmallow_sqlalchemy/./convert.py)
25+
26+
```python
27+
# convert.py
28+
import inspect
29+
import functools
30+
import warnings
31+
32+
import uuid
33+
import marshmallow as ma
34+
from marshmallow import validate, fields
35+
~~from sqlalchemy.dialects import postgresql, mysql, mssql
36+
from sqlalchemy.orm import SynonymProperty
37+
import sqlalchemy as sa
38+
39+
from .exceptions import ModelConversionError
40+
from .fields import Related, RelatedList
41+
42+
43+
def _is_field(value):
44+
return isinstance(value, type) and issubclass(value, fields.Field)
45+
46+
47+
def _has_default(column):
48+
return (
49+
column.default is not None
50+
or column.server_default is not None
51+
or _is_auto_increment(column)
52+
)
53+
54+
55+
def _is_auto_increment(column):
56+
return column.table is not None and column is column.table._autoincrement_column
57+
58+
59+
def _postgres_array_factory(converter, data_type):
60+
61+
62+
## ... source file abbreviated to get to mssql examples ...
63+
64+
65+
66+
class ModelConverter:
67+
68+
SQLA_TYPE_MAPPING = {
69+
sa.Enum: fields.Field,
70+
sa.JSON: fields.Raw,
71+
postgresql.BIT: fields.Integer,
72+
postgresql.OID: fields.Integer,
73+
postgresql.UUID: fields.UUID,
74+
postgresql.MACADDR: fields.String,
75+
postgresql.INET: fields.String,
76+
postgresql.CIDR: fields.String,
77+
postgresql.JSON: fields.Raw,
78+
postgresql.JSONB: fields.Raw,
79+
postgresql.HSTORE: fields.Raw,
80+
postgresql.ARRAY: _postgres_array_factory,
81+
postgresql.MONEY: fields.Decimal,
82+
postgresql.DATE: fields.Date,
83+
postgresql.TIME: fields.Time,
84+
mysql.BIT: fields.Integer,
85+
mysql.YEAR: fields.Integer,
86+
mysql.SET: fields.List,
87+
mysql.ENUM: fields.Field,
88+
mysql.INTEGER: fields.Integer,
89+
mysql.DATETIME: fields.DateTime,
90+
~~ mssql.BIT: fields.Integer,
91+
}
92+
DIRECTION_MAPPING = {"MANYTOONE": False, "MANYTOMANY": True, "ONETOMANY": True}
93+
94+
def __init__(self, schema_cls=None):
95+
self.schema_cls = schema_cls
96+
97+
@property
98+
def type_mapping(self):
99+
if self.schema_cls:
100+
return self.schema_cls.TYPE_MAPPING
101+
else:
102+
return ma.Schema.TYPE_MAPPING
103+
104+
def fields_for_model(
105+
self,
106+
model,
107+
*,
108+
include_fk=False,
109+
include_relationships=False,
110+
fields=None,
111+
exclude=None,
112+
base_fields=None,
113+
dict_cls=dict,
114+
):
115+
116+
117+
## ... source file continues with no further mssql examples...
118+
119+
```
120+
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
title: sqlalchemy.dialects mysql code examples
2+
category: page
3+
slug: sqlalchemy-dialects-mysql-examples
4+
sortorder: 500031001
5+
toc: False
6+
sidebartitle: sqlalchemy.dialects mysql
7+
meta: Python example code for the mysql function from the sqlalchemy.dialects module of the SQLAlchemy project.
8+
9+
10+
mysql is a function within the sqlalchemy.dialects module of the SQLAlchemy project.
11+
12+
13+
## Example 1 from marshmallow-sqlalchemy
14+
[marshmallow-sqlalchemy](https://github.com/marshmallow-code/marshmallow-sqlalchemy)
15+
([project documentation](https://marshmallow-sqlalchemy.readthedocs.io/en/latest/))
16+
is a code library that makes it easier to use
17+
[SQLAlchemy](/sqlalchemy.html) with the
18+
[Marshmallow](https://marshmallow.readthedocs.io/en/stable/)
19+
data serialization tool.
20+
21+
The marshmallow-sqlalchemy project is provided as open source under the
22+
[MIT license](https://github.com/marshmallow-code/marshmallow-sqlalchemy/blob/dev/LICENSE).
23+
24+
[**marshmallow-sqlalchemy / src/marshmallow_sqlalchemy / convert.py**](https://github.com/marshmallow-code/marshmallow-sqlalchemy/blob/dev/src/marshmallow_sqlalchemy/./convert.py)
25+
26+
```python
27+
# convert.py
28+
import inspect
29+
import functools
30+
import warnings
31+
32+
import uuid
33+
import marshmallow as ma
34+
from marshmallow import validate, fields
35+
~~from sqlalchemy.dialects import postgresql, mysql, mssql
36+
from sqlalchemy.orm import SynonymProperty
37+
import sqlalchemy as sa
38+
39+
from .exceptions import ModelConversionError
40+
from .fields import Related, RelatedList
41+
42+
43+
def _is_field(value):
44+
return isinstance(value, type) and issubclass(value, fields.Field)
45+
46+
47+
def _has_default(column):
48+
return (
49+
column.default is not None
50+
or column.server_default is not None
51+
or _is_auto_increment(column)
52+
)
53+
54+
55+
def _is_auto_increment(column):
56+
return column.table is not None and column is column.table._autoincrement_column
57+
58+
59+
def _postgres_array_factory(converter, data_type):
60+
return functools.partial(
61+
fields.List, converter._get_field_class_for_data_type(data_type.item_type)
62+
)
63+
64+
65+
class ModelConverter:
66+
67+
SQLA_TYPE_MAPPING = {
68+
sa.Enum: fields.Field,
69+
sa.JSON: fields.Raw,
70+
postgresql.BIT: fields.Integer,
71+
postgresql.OID: fields.Integer,
72+
postgresql.UUID: fields.UUID,
73+
postgresql.MACADDR: fields.String,
74+
postgresql.INET: fields.String,
75+
postgresql.CIDR: fields.String,
76+
postgresql.JSON: fields.Raw,
77+
postgresql.JSONB: fields.Raw,
78+
postgresql.HSTORE: fields.Raw,
79+
postgresql.ARRAY: _postgres_array_factory,
80+
postgresql.MONEY: fields.Decimal,
81+
postgresql.DATE: fields.Date,
82+
postgresql.TIME: fields.Time,
83+
~~ mysql.BIT: fields.Integer,
84+
~~ mysql.YEAR: fields.Integer,
85+
~~ mysql.SET: fields.List,
86+
~~ mysql.ENUM: fields.Field,
87+
~~ mysql.INTEGER: fields.Integer,
88+
~~ mysql.DATETIME: fields.DateTime,
89+
mssql.BIT: fields.Integer,
90+
}
91+
DIRECTION_MAPPING = {"MANYTOONE": False, "MANYTOMANY": True, "ONETOMANY": True}
92+
93+
def __init__(self, schema_cls=None):
94+
self.schema_cls = schema_cls
95+
96+
@property
97+
def type_mapping(self):
98+
if self.schema_cls:
99+
return self.schema_cls.TYPE_MAPPING
100+
else:
101+
return ma.Schema.TYPE_MAPPING
102+
103+
def fields_for_model(
104+
self,
105+
model,
106+
*,
107+
include_fk=False,
108+
include_relationships=False,
109+
fields=None,
110+
exclude=None,
111+
base_fields=None,
112+
dict_cls=dict,
113+
114+
115+
## ... source file continues with no further mysql examples...
116+
117+
```
118+

0 commit comments

Comments
 (0)