Advertisement
AntonioVillanueva

basic auth RESTfull web flask pyhton

Jan 10th, 2023
738
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.25 KB | None | 0 0
  1. """ serveur REST web ,avec base de données basic AUTH
  2. getAllEmp
  3. curl -i http://localhost:5000/axiome/employe
  4. getEmp
  5. curl -i http://localhost:5000/axiome/employe/{$id}
  6. default
  7. curl -i http://localhost:5000
  8. updateEmp
  9. curl -i -H "Content-type: application/json" -X PUT -d '{"title":"esclave"}' http://localhost:5000/axiome/employe/1 -u"axiome:concept"
  10. createEmp
  11. curl -i -H "Content-type: application/json" -X POST -d '{"id":"69","name":"Angus","title":"guitar"}' http://localhost:5000/axiome/employe -u"axiome:concept"
  12. Delete
  13. curl -i -X Delete http://localhost:5000/axiome/employe/1 -u"axiome:concept"
  14.  
  15. """
  16. from flask import Flask
  17. from flask_httpauth import HTTPBasicAuth #pip install Flask-HTTPAuth
  18. from flask import jsonify
  19. from flask import request
  20. from werkzeug.security import generate_password_hash, check_password_hash
  21.  
  22. app = Flask(__name__)
  23.  
  24. auth = HTTPBasicAuth()
  25.  
  26. base_address="axiome"
  27. hostname ="localhost"
  28.  
  29. """ login:pwd"""
  30. users = {
  31.     "axiome": generate_password_hash("concept"),
  32.     "tony": generate_password_hash("icaro")
  33. }
  34.  
  35.  
  36. employesDB=[
  37.      {
  38.      'id':'1',
  39.      'name':'Liberto Zaragoza',
  40.      'title':'pdg'
  41.      },
  42.      {
  43.      'id':'2',
  44.      'name':'Gilles Pignatta',
  45.      'title':'développeur'
  46.      },
  47.      {
  48.      'id':'3',
  49.      'name':'Antonio Villanueva',
  50.      'title':'développeur'
  51.      },
  52.      {
  53.      'id':'4',
  54.      'name':'Franck Clerissi',
  55.      'title':'Charge d affaires '
  56.      }
  57.  ]
  58.  
  59. @auth.verify_password
  60. def verify_password(username, password):
  61.     if username in users and \
  62.             check_password_hash(users.get(username), password):
  63.         return username
  64.  
  65.  
  66. @app.route("/")
  67. def default():
  68.     """page Web par défaut """
  69.     return jsonify({'Base Web address':base_address})
  70.  
  71. @app.route('/axiome/employe',methods=['GET'])
  72. def getAllEmp():
  73.     """renvoie toute la base de données """
  74.     return jsonify({'emps':employesDB})
  75.    
  76. @app.route('/axiome/employe/<empId>',methods=['GET'])
  77. def getEmp(empId):
  78.     """retourner un seul employé <empId> """
  79.     usr = [ emp for emp in employesDB if (emp['id'] == empId) ]
  80.     return jsonify({'employe':usr})    
  81.  
  82. @app.route('/axiome/employe',methods=['POST'])
  83. @auth.login_required
  84. def createEmp():
  85.     """ Créer un nouvel employé"""
  86.     dat = {
  87.     'id':request.json['id'],
  88.     'name':request.json['name'],
  89.     'title':request.json['title']
  90.     }
  91.     employesDB.append(dat)
  92.     return jsonify(dat)
  93.  
  94. @app.route('/axiome/employe/<empId>',methods=['PUT'])
  95. @auth.login_required
  96. def updateEmp(empId):
  97.     """mettre à jour un employé dans la base de données """
  98.     em = [ emp for emp in employesDB if (emp['id'] == empId) ]
  99.  
  100.     print ("updateEmp ",em)
  101.     if 'name' in request.json :
  102.         em[0]['name'] = request.json['name']
  103.        
  104.     if 'title' in request.json:
  105.         em[0]['title'] = request.json['title']
  106.        
  107.     return jsonify({'emp':em[0]})  
  108.  
  109. @app.route('/axiome/employe/<empId>',methods=['DELETE'])
  110. @auth.login_required
  111. def deleteEmp(empId):
  112.     """Efface employe dans employeeDB """
  113.     em = [ emp for emp in employesDB if (emp['id'] == empId) ]
  114.     if len(em) == 0:#Element vide pas trouve ...
  115.         return jsonify({'response':'Erreur employe '+empId+' n \'existe pas' })
  116.        
  117.     employesDB.remove(em[0]) #Efface id num        
  118.     return jsonify({'response':'delete employe'+empId})
  119.  
  120. if __name__ == "__main__":
  121.     #app.run()
  122.      app.run( host=hostname,port=5000)
  123.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement