Chambers
-- -- --

How to create a function that adds a new field to a table with the field’s name as a parameter?

Anonymous in /c/coding_help

790
Hi all,<br><br>I’m a Python beginner and I’m trying to create an API with Flask. This is my first “real” application. I have a table and I want to update this table by adding a new field to this table. The name of the field will be given as a parameter with POSTMAN.<br><br>So my problem is how I can add new field with field name as a parameter.<br><br>If I want to create a table my function is like this:<br><br>```<br>from flask import jsonify, request<br>from flask.views import MethodView<br>from commit_message_generator.schema import table_schema, base_schema<br>from commit_message_generator.db import db, db_connection<br>from marshmallow import ValidationError<br>from sqlalchemy import MetaData, text<br>from flask_bcrypt import Bcrypt<br>bc = Bcrypt()<br><br>class CreateTableAPI(MethodView):<br> def post(self):<br> try:<br> data = self.schema.load(request.json)<br> except ValidationError as err:<br> return {"Validation Error" : err}, 400, {'Content-Type': 'application/json; charset=utf-8'}<br><br> try:<br> conn = db_connection()<br> meta = MetaData()<br> table = db.Table(data['table_name'], meta, *[getattr(db, field_type) for field_type in data["field_types"]])<br> table.create(conn, checkfirst=True)<br> except Exception as e:<br> print(e)<br> return jsonify({"error": "Wrong column types"}), 400<br><br> return self.schema.dump(data), 201<br>```<br><br>I create a table with the given table names and field types. I want to add a new field and the field types for this table but with the field’s name as a parameter.<br><br>So how I can add a new column with the column name as a parameter?<br><br>Here is the function for add new field which throws “Unrecognized argument(s): \[field_name\]”<br><br>```<br> def post(self):<br> try:<br> data = self.schema.load(request.json)<br> except ValidationError as err:<br> return {"Validation Error" : err}, 400, {'Content-Type': 'application/json; charset=utf-8'}<br><br> try:<br> conn = db_connection()<br> table_name = data["table_name"]<br> meta = MetaData()<br> new_column = db.Column(data["field_name"], db.String())<br> with db.engine.begin() as conn:<br> conn.execute(<br> text("ALTER TABLE {} ADD COLUMN {} {}".format(table_name, data["field_name"], data["field_type"]))<br> )<br> except Exception as e:<br> return jsonify({"error": "Table doesn't exists"}), 400<br><br> return self.schema.dump(data), 201<br>```<br><br>data\[“field_name”\] gives the name and data\[“field_type”\] gives the type of the new field.<br><br>If you have any ideas or solutions please comment below. Any help would be great. Thank you.<br><br>\*Edit: db = sqlalchemy

Comments (15) 24536 👁️