Commit a39c19ec authored by Wandt's avatar Wandt

REST-API

parent be38c10f
Pipeline #23992 passed with stages
in 1 minute and 10 seconds
FROM debian:10.4
RUN apt-get update && apt-get upgrade
RUN apt-get update && apt-get upgrade -y
RUN apt-get install python3-pip -y
RUN apt-get install vim -y
RUN pip3 install --upgrade python-gitlab
RUN apt-get install curl -y
RUN apt-get install python-requests -y
RUN apt-get install python3-flask -y
RUN apt-get install python3-sqlalchemy -y
\ No newline at end of file
RUN pip3 install flask_sqlalchemy
RUN pip3 install flask_marshmallow
RUN pip3 install marshmallow-sqlalchemy
\ No newline at end of file
import gitlab
import requests
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from app import app, db
from db_model import User,user_schema,users_schema
import os
#Serververbindung
gl = gitlab.Gitlab('https://git.zib.de/', private_token='4zG-g_br5Ahv722zWff1')
gl.auth()
#Durchsuchen der Projekte (Nach Projektnamen CI)
project = gl.projects.list(search='CI')
#Ausgabe des Projekts
print(project)
#User erstellen
@app.route('/user', methods=['POST'])
def add_user():
vname = request.json['vname']
nname = request.json['nname']
username = request.json['username']
aktiv = request.json['aktiv']
#triggert die Pipeline
rsp = requests.post('https://git.zib.de/api/v4/projects/1450/trigger/pipeline',
data={'token': 'c5580634c935e4c97804c9db8ab6b3', 'ref': 'master'})
new_user = User(vname, nname, username, aktiv)
#get request
rsp = requests.get('https://git.zib.de/azubi-2019/docker/-/issues/2')
print(rsp)
\ No newline at end of file
db.session.add(new_user)
db.session.commit()
return user_schema.jsonify(new_user)
#Ausgabe aller User
@app.route('/user', methods=['GET'])
def get_users():
all_users = User.query.all()
result = users_schema.dump(all_users)
return jsonify(result)
#Ausgabe eines einzelnen Users
@app.route('/user/<id>', methods=['GET'])
def get_user(id):
user = User.query.get(id)
return user_schema.jsonify(user)
#Bearbeiten eines Users
@app.route('/user/<id>', methods=['PUT'])
def update_user(id):
user = User.query.get(id)
vname = request.json['vname']
nname = request.json['nname']
username = request.json['username']
aktiv = request.json['aktiv']
user.vname = vname
user.nname = nname
user.username = username
user.aktiv = aktiv
db.session.commit()
return user_schema.jsonify(user)
#Löschen eines Users
@app.route('/user/<id>', methods=['DELETE'])
def delete_user(id):
user = User.query.get(id)
db.session.delete(user)
db.session.commit()
return user_schema.jsonify(user)
# Run Server
if __name__ == '__main__':
app.run(host = "0.0.0.0", debug = True)
\ No newline at end of file
import requests
import json
#Get Request
def get():
print("GET")
url = "http://0.0.0.0:5000/user"
r = requests.get(url)
print(r.status_code)
print(r.content)
#Post Request: User Create
def post():
print("POST")
url = "http://0.0.0.0:5000/user"
data = {'vname': 'harry', 'nname': 'potter', 'username':'hpotter','aktiv':'ja'}
header = {'Content-type': 'application/json'}
r = requests.post(url,data=json.dumps(data), headers=header)
print(r.status_code)
print(r.content)
#Delete Request: User Delete
def delete():
print("DELETE")
url = "http://0.0.0.0:5000/user/1"
r = requests.delete(url)
print(r.status_code)
print(r.content)
#Put Request: User Update
def put():
print("PUT")
url = "http://0.0.0.0:5000/user/1"
data = {'vname': 'kevin', 'nname': 'mueller', 'username':'kmueller','aktiv':'nein'}
header = {'Content-type': 'application/json'}
r = requests.put(url,data=json.dumps(data), headers=header)
print(r.status_code)
print(r.content)
if __name__ == '__main__':
get()
post()
put()
delete()
get()
\ No newline at end of file
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
#Erstellen der App
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
#Erstellen der Datenbank
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'db.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
ma = Marshmallow(app)
\ No newline at end of file
No preview for this file type
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from app import db, ma
import os
#User Class/Model
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
vname = db.Column(db.String(100))
nname = db.Column(db.String(100))
username = db.Column(db.String(100))
aktiv = db.Column(db.String(4))
def __init__(self, vname, nname, username, aktiv):
self.vname = vname
self.nname = nname
self.username = username
self.aktiv = aktiv
#User Schema
class UserSchema(ma.Schema):
class Meta:
fields = ('id', 'vname', 'nname', 'username', 'aktiv')
#Initialisieren des Schemas
user_schema = UserSchema()
users_schema = UserSchema(many=True)
\ No newline at end of file
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
# Init app
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
# Database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'db.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Init db
db = SQLAlchemy(app)
# Init ma
ma = Marshmallow(app)
# Product Class/Model
class Product(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), unique=True)
description = db.Column(db.String(200))
price = db.Column(db.Float)
qty = db.Column(db.Integer)
def __init__(self, name, description, price, qty):
self.name = name
self.description = description
self.price = price
self.qty = qty
# Product Schema
class ProductSchema(ma.Schema):
class Meta:
fields = ('id', 'name', 'description', 'price', 'qty')
# Init schema
product_schema = ProductSchema()
products_schema = ProductSchema(many=True)
# Create a Product
@app.route('/product', methods=['POST'])
def add_product():
name = request.json['name']
description = request.json['description']
price = request.json['price']
qty = request.json['qty']
new_product = Product(name, description, price, qty)
db.session.add(new_product)
db.session.commit()
return product_schema.jsonify(new_product)
# Get All Products
@app.route('/product', methods=['GET'])
def get_products():
all_products = Product.query.all()
result = products_schema.dump(all_products)
return jsonify(result) #oder return jsonify(result.data)
# Get Single Products
@app.route('/product/<id>', methods=['GET'])
def get_product(id):
product = Product.query.get(id)
return product_schema.jsonify(product)
# Update a Product
@app.route('/product/<id>', methods=['PUT'])
def update_product(id):
product = Product.query.get(id)
name = request.json['name']
description = request.json['description']
price = request.json['price']
qty = request.json['qty']
product.name = name
product.description = description
product.price = price
product.qty = qty
db.session.commit()
return product_schema.jsonify(product)
# Delete Product
@app.route('/product/<id>', methods=['DELETE'])
def delete_product(id):
product = Product.query.get(id)
db.session.delete(product)
db.session.commit()
return product_schema.jsonify(product)
# Run Server
if __name__ == '__main__':
app.run(debug=True)
\ No newline at end of file
#!/usr/bin/python3
from mapping import User
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from flask import jsonify, Flask
#Verbindung aufbauen
engine = create_engine('sqlite:///benutzer.db', echo = True)
Session = sessionmaker(bind=engine)
session = Session()
app = Flask(__name__)
app.config['SECRET_KEY'] = 'test'
#Abfrage nach Objekt User
query = session.query(User)
#Methode:
def user_all():
query = session.query(User.user_id, User.nname, User.vname, User.username, User.joining, User.aktiv)
return query
def user_home():
query = session.query(User.username)
return query
def user_one(benutzer, methods =['GET', 'POST']):
query = session.query(User.user_id, User.nname, User.vname, User.username, User.joining, User.aktiv).filter(User.username == benutzer)
return query
def user_create(result):
obj = User(result['user_id'], result['nname'], result['vname'], result['username'], result['joining'], result['aktiv'], result['password'])
session.add(obj)
session.commit()
@app.route('/home')
def home():
cols = ['Username']
data = session.query(User.username)
result = [{col: getattr(d, col) for col in cols} for d in data]
return jsonify(result=result)
if __name__ == '__main__':
app.run(host = "0.0.0.0", debug = True)
\ No newline at end of file
import requests
insert = requests.post('http://0.0.0.0:5000/product',
data={"name": "Test Product", "description": "this is a test product",
"rice": 350,
"qty": 100})
\ No newline at end of file
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, String , Date, MetaData
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:///benutzer.db', echo = True)
#Beschreiben der Tabellen
Base = declarative_base() #Base Class wird erstellt; diese enthält eine Sammlung von Klassen und Tabellen, welche in Verbindung zur Basis stehen
class User(Base):
__tablename__ = 'user'
user_id = Column(Integer, primary_key = True)
nname = Column(String(25))
vname = Column(String(25))
username = Column(String(25))
joining = Column(String(25))
aktiv = Column(String(4))
password = Column(String(200))
def __init__ (self, user_id, nname, vname, username, joining, aktiv, password):
self.user_id = user_id
self.nname = nname
self.vname = vname
self.username = username
self.joining = joining
self.aktiv = aktiv
self.password = password
def __repr__(self):
return "<User (user_id = '%s', nname = '%s', vname = '%s' , username = '%s', joining = '%s', aktiv = '%s', password ='%s')>" % (self.user_id, self.nname, self.vname, self.username, self.joining, self.aktiv, self.password)
Base.metadata.create_all(engine)
\ No newline at end of file
from sqlalchemy import create_engine
from mapping import User
from sqlalchemy.orm import sessionmaker
#Verbindung aufbauen
engine = create_engine('sqlite:///benutzer.db', echo = True)
Session = sessionmaker(bind=engine)
session = Session()
#Abfrage: Alle User
query = session.query(User)
all = query.all()
print(all)
\ No newline at end of file
import requests
#Anfrage: Ausgabe aller User
request = requests.get('http://0.0.0.0:5000/home')
print(request)
\ No newline at end of file
import yaml
import sqlalchemy
from sqlalchemy import create_engine
from mapping import User
from sqlalchemy.orm import sessionmaker
#Verbindung aufbauen
engine = create_engine('sqlite:///benutzer.db', echo = True)
Session = sessionmaker(bind=engine)
session = Session()
#User aus YAML File importieren
with open('users.yaml') as user_file:
users = yaml.load(user_file)
#Erstellen der User Objekte
for user in users:
obj = User(user['user_id'], user['nname'], user['vname'], user['username'], user['joining'], user['aktiv'], user['password'])
session.add(obj)
session.commit()
\ No newline at end of file
-
user_id: 1
vname: Miriam
nname: Duscha
username: dramalama
joining: 20.03.1990
aktiv: ja
password: test
-
user_id: 2
vname: Fabian
nname: Wandt
username: scriptkiddie
joining: 13.03.2005
aktiv: nein
password: test
-
user_id: 3
vname: Chris
nname: Linnemann
username: erdbeere
joining: 15.06.2000
aktiv: ja
password: test
-
user_id: 4
vname: Kilian
nname: Hassatzky
username: cptkiwi
joining: 15.06.2000
aktiv: ja
password: test
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment