-
Notifications
You must be signed in to change notification settings - Fork 0
/
mfa
executable file
·942 lines (774 loc) · 24.7 KB
/
mfa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
#!/bin/bash
make_pyfiles () {
cat > .gitignore << EOF
# Created by https://www.gitignore.io/v1/example,visualstudiocode,virtualenv
# Edit at https://www.gitignore.io/?templates=python,visualstudiocode,virtualenv
### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# pyenv
.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# Mr Developer
.mr.developer.cfg
.project
.pydevproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
### VirtualEnv ###
# Virtualenv
# http://iamzed.com/2009/05/07/a-primer-on-virtualenv/
pyvenv.cfg
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
pip-selfcheck.json
### VisualStudioCode ###
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
### VisualStudioCode Patch ###
# Ignore all local history of files
.history
# End of https://www.gitignore.io/v1/example,visualstudiocode,virtualenv
#temporal archives
*~
#poetry
poetry.lock
#pyC
*.pyc
#coderuner
tempCodeRunnerFile.py
EOF
cat > server.py << EOF
from flask import Flask
def create_app(config_class, *blueprints):
app = Flask(__name__)
app.config.from_object(config_class)
register_errorhandlers(app)
register_blueprints(app, *blueprints)
register_extensions(app)
return app
def register_blueprints(app: Flask, *args):
for blueprint in args:
app.register_blueprint(blueprint)
def register_extensions(app: Flask):
from models import ma
from models import db, create_database
db.init_app(app)
ma.init_app(app)
with app.app_context():
create_database()
db.create_all()
def register_errorhandlers(app: Flask):
from flask import jsonify
from sqlalchemy.exc import SQLAlchemyError
# * Errors in db
@app.errorhandler(SQLAlchemyError)
def sql_alchemy_error(err):
app.logger.exception(err)
return jsonify({"Request body error": f"{err}"}), 400
@app.errorhandler(Exception)
def exception(err):
app.logger.exception(err)
return jsonify({"error": f"{err}"}), 400
# * Error 401
@app.errorhandler(401)
def method_not_unauthorized(err):
app.logger.exception(err)
return jsonify({"Authenticate": "Could not verify"}), 401
# * Error 403
@app.errorhandler(403)
def access_denied(err):
app.logger.exception(err)
return jsonify({"Permission": "Acces denied for this resource"}), 403
# * Error 404
@app.errorhandler(404)
def page_not_found(err):
app.logger.exception(err)
return jsonify({"Message": "This page could not be found"}), 404
# * Error 405
@app.errorhandler(405)
def method_not_allowed(err):
app.logger.exception(err)
return (
jsonify({"Message": "The method is not allowed for the requested URL"}),
405,
)
EOF
cat > run.py << EOF
from server import create_app
from config import DevConfig
from routes.example_routes import example
app = create_app(DevConfig, example)
if __name__ == "__main__":
app.run()
EOF
cat > config/__init__.py << EOF
"""Application configuration."""
import os
from models.table_example import TableExample
class Config:
"""Base configuration."""
SECRET_KEY = os.environ.get("APP_SECRET", "secret-key") # TODO: Change me
APP_DIR = os.path.abspath(os.path.dirname(__file__)) # This directory
PROJECT_ROOT = os.path.abspath(os.path.join(APP_DIR, os.pardir))
CACHE_TYPE = "simple" # Can be "memcached", "redis", etc.
EGINE_URI = "mysql://root:" + os.environ["PASSMARIA"] + "@localhost"
# * EGINE_URI = 'mysql://root:@localhost'
SQLALCHEMY_TRACK_MODIFICATIONS = False
TABLE_VALIDATE_TOKEN = TableExample
CORS_ORIGIN_WHITELIST = [
"http://0.0.0.0:4100",
"http://localhost:4100",
"http://0.0.0.0:8000",
"http://localhost:8000",
"http://0.0.0.0:4200",
"http://localhost:4200",
"http://0.0.0.0:4000",
"http://localhost:4000",
"http://0.0.0.0:5000",
"http://localhost:5000",
]
class ProdConfig(Config):
"""Production configuration."""
ENV = "prod"
DEBUG = False
DB_NAME = "example"
SQLALCHEMY_DATABASE_URI = f"{Config.EGINE_URI}/{DB_NAME}"
class DevConfig(Config):
"""Development configuration."""
ENV = "dev"
DEBUG = True
DB_NAME = "example"
SQLALCHEMY_DATABASE_URI = f"{Config.EGINE_URI}/{DB_NAME}"
CACHE_TYPE = "simple" # Can be "memcached", "redis", etc.
class TestConfig(Config):
"""Test configuration."""
TESTING = True
DEBUG = True
DB_NAME = "TestExample"
SQLALCHEMY_DATABASE_URI = f"{Config.EGINE_URI}/{DB_NAME}"
EOF
cat > helpers/validations.py << EOF
from flask import current_app as app
from flask import jsonify, request
import jwt
from functools import wraps
from models import Schema
from marshmallow import ValidationError
def token_required(**parameters):
""" Validate jwt token
Args:
**kwargs: Arbitrary keyword arguments.
Parameters Args:
table: Registered Users Lookup Table. Default to app.config['TABLE_VALIDATE_TOKEN']
key: key to decipher jwt token. Default to app.config['SECRET_KEY']
"""
def inner_function(f):
@wraps(f)
def wrapper(*args, **kwargs):
token: str = request.headers.get('x-access-token', None)
if not token:
return jsonify({'message': 'Token is missing!'}), 401
table = parameters.get('table', app.config['TABLE_VALIDATE_TOKEN'])
key = parameters.get('key', app.config['SECRET_KEY'])
print(key)
try:
data = jwt.decode(token, key)
current_user = table.query.filter_by(id=data['id']).first()
except (jwt.ExpiredSignature, jwt.InvalidSignatureError, jwt.DecodeError):
return jsonify({'message': 'Token is invalid!'}), 401
return f(*args, current_user, **kwargs)
return wrapper
return inner_function
def validate_json(schema: Schema):
""" Validate json sent
Args:
schema (Schema): marshmallow Schema for validate json
"""
def inner_function(f):
@wraps(f)
def wrapper(*args, **kwargs):
try:
schema.load(request.json)
except ValidationError as err:
return err.messages, 400
return f(*args, **kwargs)
return wrapper
return inner_function
EOF
cat > helpers/output.py << EOF
from flask import jsonify
from functools import wraps
def response(f):
""" encrypt response """
@wraps(f)
def wrapper(*args, **kwargs):
plain_json, error_code = f(*args, **kwargs)
return jsonify(plain_json), error_code
return wrapper
EOF
cat > models/__init__.py << EOF
from flask_sqlalchemy import SQLAlchemy, Model
from flask_marshmallow import Marshmallow
from flask import abort, current_app as app
from sqlalchemy import exc, event
from datetime import datetime
from werkzeug.security import generate_password_hash
class DBUtils(Model):
""" Utils for database"""
def save(self):
""" Save new record """
db.session.add(self)
try:
db.session.commit()
except exc.SQLAlchemyError:
db.session.rollback()
raise exc.SQLAlchemyError("Error trying to save or update resource")
@classmethod
def get_by_id(cls, id, *args):
"""get record for id
Args:
table(Model): table for search
id: id for search
args: other arguments
Returns:
object: requested data
int: http error 404
"""
return cls.query.get_or_404(id)
@classmethod
def all(cls, *args):
"""get all records
Args:
table(Model): table for search
args: other arguments
Returns:
object: requested records
int: http error 404
"""
list_records = cls.query.all()
return list_records if list_records else abort(404)
@classmethod
def paginate(cls, page: int, per_page: int, *args):
"""paginate all records
Args:
table(Model): table for search
page(int): size to page
per_page(int): page to show
args: other arguments
Returns:
object: requested records
int: http error 404
"""
paginate = cls.query.paginate(page, per_page, False)
return paginate if paginate.items else abort(404)
def delete(self, *args):
""" Delete record """
db.session.delete(self)
try:
db.session.commit()
except exc.SQLAlchemyError:
db.session.rollback()
raise exc.SQLAlchemyError("Error trying to delete resource")
db = SQLAlchemy(model_class=DBUtils)
ma = Marshmallow()
Model = db.Model
Schema = ma.Schema
def create_database():
"""Crate database"""
engine = db.create_engine(app.config["EGINE_URI"], {})
engine.execute(f"CREATE DATABASE IF NOT EXISTS {app.config['DB_NAME']}")
from .table_example import TableExample
EOF
cat > models/login.py << EOF
from . import ma, Schema
from marshmallow import validate
class LoginSchema(Schema):
email = ma.Email(required=True)
password = ma.Str(validate=validate.Length(min=8), required=True)
EOF
cat > models/table_example.py << EOF
from . import db, Model, ma, Schema
from werkzeug.security import generate_password_hash, check_password_hash
from marshmallow import validate
class TableExample(Model):
__tablename__ = 'TableExample'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password = db.Column(db.String(200), nullable=False)
def __init__(self, fields: dict, *args):
self.changes(fields)
def changes(self, fields: dict, *args):
self.name = fields.get('name')
self.password = self.__generate_password(fields.get('password'))
self.email = fields.get('email')
@staticmethod
def __generate_password(password: str) -> str:
return generate_password_hash(password)
def compare_passwords(self, password: str) -> bool:
return check_password_hash(self.password, password)
class TableExample_Schema(Schema):
name = ma.Str(validate=validate.Length(min=1), required=True)
email = ma.Email(required=True)
password = ma.Str(validate=validate.Length(min=4), load_only=True, required=True)
class Meta:
fields = ('id', 'name', 'email', 'password')
EOF
cat > routes/__init__.py << EOF
from flask import Blueprint
example = Blueprint('example', __name__)
EOF
cat > routes/example_routes.py << EOF
from . import example
from models.table_example import TableExample, TableExample_Schema
from routes.utils.create_routes import create_endpoints
create_endpoints(
example,
"example",
TableExample,
TableExample_Schema,
login_endpoint=True
)
EOF
cat > routes/utils/api_template.py << EOF
from flask.views import MethodView
from flask import current_app as app
from models import Model, Schema
from routes.utils.http_methods.get_request import GetRequest
from routes.utils.http_methods.post_request import PostRequest
from routes.utils.http_methods.put_request import PutRequest
from routes.utils.http_methods.delete_request import DeleteRequest
from config.login_config import LoginConfig
class MethodsApi(MethodView, GetRequest, PostRequest, PutRequest, DeleteRequest):
""" Class for control to endpoints """
def __init__(
self, table_model: Model, table_schema: Schema, login_config: LoginConfig = None
):
"""Class for http methods
Args:
table_model (Model): sqlalchemy model
table_schema (Schema): marshmallow schema
login_config (LoginConfig): login config
"""
result = table_schema()
results = table_schema(many=True)
if not login_config.key:
login_config.key = app.config["SECRET_KEY"]
GetRequest.__init__(self, table_model, result, results)
PostRequest.__init__(self, table_model, result, login_config)
PutRequest.__init__(self, table_model, result)
DeleteRequest.__init__(self, table_model, result)
EOF
cat > routes/utils/create_routes.py <<EOF
from routes.utils.api_template import MethodsApi
from config.login_config import LoginConfig
def create_endpoints(
blueprint,
noun,
table_model,
table_schema,
login_endpoint=False,
login_config=LoginConfig(),
endpoints=[],
):
"""Create routes standars
Args:
blueprint (object): blueprint or object flask app
noun (str): noun to create endpoints and method view name.
table_model (Model): sqlalchemy model.
table_schema (Schema): marshmallow schema.
login_endpoint (bool, optional): Create login endpoint. Defaullt to False.
login_config (dict, optional): receives configuration parameters to login.
endpoints (list, optional): List to endpoints ([['/url', ['GET']]]). Default generate endpoints with noun.
Examples:
basic usage:
create_endpoints(
table_model=SomeModel,
table_schema=SomeSchema,
blueprint=some_blueprint,
noun="v1/somenoun",
login_endpoint=True)
customize endpoints:
create_endpoints(
table_model=SomeModel,
table_schema=SomeSchema,
blueprint=some_blueprint,
noun="v1/somenoun",
endpoints=[['/api/v1/somenoun', ['GET','POST']])
"""
view_func = MethodsApi.as_view(f"{noun}_api", table_model, table_schema, login_config)
endpoint_list = endpoints if endpoints else get_endpoints(noun, login_endpoint)
for i in endpoint_list:
blueprint.add_url_rule(i[0], methods=i[1], view_func=view_func)
def get_endpoints(noun: str, login: bool) -> list:
endpoint_list = [
[f"/api/{noun}/", ["POST", "GET"]],
[f"/api/{noun}/<int:id>", ["GET", "PUT", "DELETE"]],
]
if login:
endpoint_list.insert(0, [f"/api/{noun}/login", ["POST"]])
return endpoint_list
EOF
cat > config/login_config.py << EOF
import jwt
import datetime
from models.login import LoginSchema
class LoginConfig:
def __init__(
self,
search_field="email",
password_field="password",
schema=LoginSchema,
key=None,
):
self.search_field = search_field
self.password_field = password_field
self.schema = schema
self.__key = key
@property
def key(self):
""" get symmetric key """
return self.__key
@key.setter
def key(self, key):
""" set symmetric key """
self.__key = key
def create_token(self, model, auth_data: dict):
"""Create new session and execute post action(optional)
Returns:
token (json): jwt
"""
search_value = auth_data[self.search_field]
search_dict = {self.search_field: search_value}
user = model.query.filter_by(**search_dict).first()
if not user:
return {"Authenticate": "Could not verify"}, 401
password = auth_data[self.password_field]
if user.compare_passwords(password):
token = jwt.encode(
{
"id": user.id,
"exp": datetime.datetime.utcnow() + datetime.timedelta(minutes=30),
},
self.login_config.key,
)
return {"token": token.decode("UTF-8")}, 201
return {"Authenticate": "Could not verify"}, 401
EOF
cat > routes/utils/http_methods/delete_request.py << EOF
from helpers.validations import token_required
from helpers.output import response
class DeleteRequest:
def __init__(self, table_model, result):
self.__table_model = table_model
self.__result = result
@token_required()
@response
def delete(self, current_user, id):
"""Delete record
Args:
current_user (object): Contains the data of the logged in user
id (int, optional): ID registration
Returns:
json: deleted record
"""
registry_delete = self.__table_model.get_by_id(id, current_user)
registry_delete.delete(current_user)
return self.__result.dump(registry_delete), 200
EOF
cat > routes/utils/http_methods/get_request.py << EOF
from helpers.validations import token_required
from helpers.output import response
from flask import request
class GetRequest:
def __init__(self, table_model, result, results):
self.__table_model = table_model
self.__result = result
self.__results = results
@token_required()
@response
def get(self, current_user, id=None):
"""Method http GET
Args:
current_user (object): Contains the data of the logged in user
id (int, optional): ID registration. Defaults to None.
Returns:
json: many or one registry
http error: corresponding code http error
"""
if id:
return self.get_by_id(current_user, id)
elif "page" in request.args.keys():
page = int(request.args.get("page", type=int, default=1))
per_page = int(request.args.get("size", type=int, default=10))
return self.get_pagination(page, per_page, current_user)
return self.get_all(current_user)
def get_all(self, current_user: object):
registrys_list = self.__table_model.all(current_user)
return {"results": self.__results.dump(registrys_list)}, 200
def get_by_id(self, current_user: object, id: int):
one_registry = self.__table_model.get_by_id(id, current_user)
return self.__result.dump(one_registry), 200
def get_pagination(self, page: int, per_page: int, current_user: object):
paginar = self.__table_model.paginate(page, per_page, current_user)
return {
"results": self.__results.dump(paginar.items),
"total-pages": paginar.pages,
}, 200
EOF
cat > routes/utils/http_methods/post_request.py << EOF
import jwt
import datetime
from flask import request, abort
from flask import current_app as app
from helpers.validations import token_required, validate_json
from helpers.output import response
class PostRequest:
def __init__(self, table_model, result, login_config):
self.login_config = login_config
self.__table_model = table_model
self.login = validate_json(login_config.schema())(self.login)
self.add = validate_json(result)(self.add)
self.__result = result
def post(self):
""" Method http GET """
rute = str(request.url_rule)
if rute.find("login") != -1:
return self.login()
return self.add()
@response
def login(self):
"""Create new session and execute post action(optional)
Returns:
token (json): jwt
"""
return self.login_config.create_token(self.__table_model, request.json)
@token_required()
@response
def add(self, current_user):
"""Add new record
Args:
current_user (object): Contains the data of the logged in user
Returns:
json: registry created
"""
new_registry = self.__table_model(request.json, current_user)
new_registry.save()
return self.__result.dump(new_registry), 201
EOF
cat > routes/utils/http_methods/put_request.py << EOF
from flask import request
from helpers.validations import token_required, validate_json
from helpers.output import response
class PutRequest:
def __init__(self, table_model, result):
self.__result = result
self.__table_model = table_model
self.put = validate_json(result)(self.put)
@token_required()
@response
def put(self, current_user, id):
"""Edit record
Args:
current_user (object): Contains the data of the logged in user
id (int, optional): ID registration
Returns:
json: edited record
"""
registry_update = self.__table_model.get_by_id(id, current_user)
registry_update.changes(request.json, current_user)
registry_update.save()
return self.__result.dump(registry_update), 200
EOF
cat > requirements.txt << EOF
flask
flask_sqlalchemy
flask_marshmallow
marshmallow-sqlalchemy
mysqlclient
pyjwt
EOF
}
poetry_install () {
poetry init -n
poetry add -D pytest Black flake8
cat requirements.txt | xargs -L 1 poetry add
rm requirements.txt
}
install_dep (){
tempfile="/tmp/install_d.log"
echo -ne "\e[97m=>\e[0m \e[31m\uf8d5\e[0m Instalando dependencias\r"
poetry_install 2>/dev/null 1>>$tempfile &
while ps |grep $! &>/dev/null; do
echo -ne "\e[97m=>\e[0m \e[32m\uf8d6\e[0m Instalando dependencias\r"
sleep 1
echo -ne "\e[97m=>\e[0m \e[31m\uf8d5\e[0m Instalando dependencias\r"
sleep 1
done
echo -ne "\e[97m=>\e[0m \e[32m\uf8d6\e[0m Dependencias Instaladas\r"
rm $tempfile
}
make_dockerfile (){
mkdir .devcontainer
cd .devcontainer
cat > devcontainer.json << EOF
{
"name": "Docker python",
"dockerFile": "Dockerfile",
"appPort": 3000,
//"postCreateCommand": "mysqld &"
"postCreateCommand": "mysqld_safe --skip-grant-tables &"
}
EOF
cat > Dockerfile << EOF
FROM python:3.8-alpine
RUN apk add --no-cache --purge -uU mysql mysql-client mariadb-dev mariadb-connector-c
RUN apk add --no-cache --virtual build-deps gcc musl-dev
RUN rm -rf /var/cache/apk/* /tmp/*
RUN pip install flask flask_sqlalchemy flask_marshmallow marshmallow-sqlalchemy mysqlclient pyjwt flask-cors
RUN apk del build-deps mariadb-dev
EXPOSE 3306
EOF
echo -e "\n\e[91m=>\e[0m \e[36m\uf308\e[0m Dokerfile Creado"
}
make_project (){
echo -e "\e[34m=>\e[0m \e[96m\ue5fc\e[0m Folders Creados"
mkdir -p routes/utils/http_methods models helpers config
echo -e "\e[35m=>\e[0m \e[33m\ue235\e[0m Pyfiles Creados"
make_pyfiles
}
while getopts n:idp flag
do
case "${flag}" in
n) projectname=${OPTARG};;
i) init=true;;
d) docker=true;;
p) poetry=true;;
*)
echo 'La vandera no existe' >&2
exit 1
;;
esac
done
if [ $init ] && [ ! $projectname ];then
make_project
if [ $docker ] && [ $poetry ];then
make_dockerfile
install_dep
elif [ $poetry ];then
install_dep
elif [ $docker ];then
make_dockerfile
fi
echo -e "\e[96m=>\e[0m \e[92m\uf00c\e[0m Inicializado"
elif [ ! $init ] && [ $projectname ];then
if [ -d $(pwd)/$projectname ];then
echo -e "\e[31m\ue009\e[0m\e[5m El proyecto ya exite en su sistema\e[0m"
else
echo -e "\e[93m=>\e[0m \e[30m\uf593\e[0m Creando API REST flask $projectname"
mkdir $projectname
cd $projectname
make_project
if [ $docker ] && [ $poetry ];then
make_dockerfile
install_dep
elif [ $poetry ];then
install_dep
elif [ $docker ];then
make_dockerfile
fi
echo -e "\e[96m=>\e[0m \e[92m\uf00c\e[0m $projectname Creado"
fi
elif [ $docker ] && [ $poetry ] && [ ! $init ] && [ ! $projectname ];then
make_dockerfile
install_dep
elif [ $docker ] && [ ! $init ] && [ ! $projectname ] && [ ! $poetry ];then
make_dockerfile
elif [ $poetry ] && [ ! $init ] && [ ! $projectname ] && [ ! $docker ];then
install_dep
else
echo -e "\e[31m\ue009\e[0m\e[5m Eror en la secuencia de vandera -n y -i no deben usarse juntas\e[0m" >&2
exit 1
fi