spacepaste

  1.  
  2. #app/__init__.py
  3. from config import CELERY_BROKER_URL
  4. celery = Celery(__name__, broker=CELERY_BROKER_URL)
  5. def create_app(config_filename):
  6. app = Flask(__name__, static_folder='templates/static')
  7. app.config.from_object(config_filename)
  8. # Init Flask-SQLAlchemy
  9. from app.basemodels import db
  10. db.init_app(app)
  11. from app.users.views import users
  12. app.register_blueprint(users, url_prefix='/api/v1/users')
  13. from app.baseviews import login_required, login1, mail
  14. from flask import render_template, send_from_directory
  15. import os
  16. # Init Flask-Mail
  17. mail.init_app(app)
  18. celery.conf.update(app.config)
  19. @app.route('/')
  20. def index():
  21. return render_template('index.html')
  22. return app
  23. #app/celeries/views.py
  24. from app import celery
  25. @celery.task
  26. def send_async_email(cel):
  27. """Background task to send an email with Flask-Mail."""
  28. with app.app_context():
  29. print("Adding")
  30. cel.add(cel)
  31. class CreateListCeleries(Resource):
  32. """http://jsonapi.org/format/#fetching
  33. A server MUST respond to a successful request to fetch an individual resource or resource collection with a 200 OK response.
  34. A server MUST respond with 404 Not Found when processing a request to fetch a single resource that does not exist, except when the request warrants a 200 OK response with null as the primary data (as described above)
  35. a self link as part of the top-level links object"""
  36. def get(self):
  37. celeries_query = Celeries.query.all()
  38. results = schema.dump(celeries_query, many=True).data
  39. return results
  40. """http://jsonapi.org/format/#crud
  41. A resource can be created by sending a POST request to a URL that represents a collection of celeries. The request MUST include a single resource object as primary data. The resource object MUST contain at least a type member.
  42. If a POST request did not include a Client-Generated ID and the requested resource has been created successfully, the server MUST return a 201 Created status code"""
  43. def post(self):
  44. raw_dict = request.get_json(force=True)
  45. try:
  46. schema.validate(raw_dict)
  47. request_dict = raw_dict['data']['attributes']
  48. cel = Celeries(
  49. request_dict['hostname'], request_dict['ipaddress'],)
  50. send_async_email.apply_async(args=[cel], countdown=30)
  51. resp = jsonify({"error": "success"})
  52. resp.status_code = 201
  53. return resp
  54. except ValidationError as err:
  55. resp = jsonify({"error": err.messages})
  56. resp.status_code = 403
  57. return resp
  58. except SQLAlchemyError as e:
  59. db.session.rollback()
  60. resp = jsonify({"error": str(e)})
  61. resp.status_code = 403
  62. return resp
  63. api.add_resource(CreateListCeleries, '.json')
  64.