From c63307e33ea44b78a0f72f7b6257426bbcd1035f Mon Sep 17 00:00:00 2001 From: "DESKTOP-RNK2HL9\\DELL" Date: Sun, 8 Sep 2024 18:07:02 +0700 Subject: [PATCH] feature/1-init-project --- backend/app.py | 10 ++++++ backend/flaskr/__init__.py | 41 +++++++++++++++++++++ backend/models.py | 5 +-- frontend/src/components/QuestionView.js | 48 ++++++++++++------------- 4 files changed, 78 insertions(+), 26 deletions(-) create mode 100644 backend/app.py diff --git a/backend/app.py b/backend/app.py new file mode 100644 index 000000000..3877c6494 --- /dev/null +++ b/backend/app.py @@ -0,0 +1,10 @@ +import os +from flaskr import create_app + +os.environ['FLASK_APP'] = 'flaskr:create_app' +os.environ['FLASK_ENV'] = 'development' + +app = create_app() + +if __name__ == '__main__': + app.run() \ No newline at end of file diff --git a/backend/flaskr/__init__.py b/backend/flaskr/__init__.py index eef4a19d8..ba18cebed 100644 --- a/backend/flaskr/__init__.py +++ b/backend/flaskr/__init__.py @@ -21,17 +21,39 @@ def create_app(test_config=None): """ @TODO: Set up CORS. Allow '*' for origins. Delete the sample route after completing the TODOs """ + #CORS(app, resources={r"*/api/*" : {origins: '*'}}) + + CORS(app) """ @TODO: Use the after_request decorator to set Access-Control-Allow """ + @app.after_request + def after_request(response): + response.headers.add('Access-Control-Allow-Headers', 'Content-Type, Authorization') + response.headers.add('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE, OPTIONS') + return response """ @TODO: Create an endpoint to handle GET requests for all available categories. """ + @app.route('/categories') + def get_categories(): + # Implement pagination + page = request.args.get('page', 1, type=int) + start = (page - 1) * 10 + end = start + 10 + + categories = Category.query.all() + formatted_categories = [category.format() for category in categories] + return jsonify({ + 'success': True, + 'categories': formatted_categories[start:end], + 'total_categories': len(formatted_categories) + }) """ @TODO: @@ -45,6 +67,25 @@ def create_app(test_config=None): ten questions per page and pagination at the bottom of the screen for three pages. Clicking on the page numbers should update the questions. """ + @app.route('/questions') + def get_questions(): + # Implement pagination + page = request.args.get('page', 1, type=int) + start = (page - 1) * 10 + end = start + 10 + + categories = Category.query.all() + formatted_categories = [category.format() for category in categories] + + questions = Question.query.all() + formatted_questions = [question.format() for question in questions] + + return jsonify({ + 'success': True, + 'questions': formatted_questions[start:end], + 'total_questions': len(formatted_questions), + 'categories': formatted_categories, + }) """ @TODO: diff --git a/backend/models.py b/backend/models.py index 3c5f56ed1..fd3176f0d 100644 --- a/backend/models.py +++ b/backend/models.py @@ -4,7 +4,7 @@ import json database_name = 'trivia' -database_path = 'postgresql://{}/{}'.format('localhost:5432', database_name) +database_path = 'postgresql://postgres:12345@{}/{}'.format('localhost:5432', database_name) db = SQLAlchemy() @@ -17,7 +17,8 @@ def setup_db(app, database_path=database_path): app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False db.app = app db.init_app(app) - db.create_all() + with app.app_context(): + db.create_all() """ Question diff --git a/frontend/src/components/QuestionView.js b/frontend/src/components/QuestionView.js index a86b1f8db..ff296f6b8 100755 --- a/frontend/src/components/QuestionView.js +++ b/frontend/src/components/QuestionView.js @@ -1,8 +1,8 @@ -import React, { Component } from 'react'; -import '../stylesheets/App.css'; -import Question from './Question'; -import Search from './Search'; -import $ from 'jquery'; +import React, { Component } from "react"; +import "../stylesheets/App.css"; +import Question from "./Question"; +import Search from "./Search"; +import $ from "jquery"; class QuestionView extends Component { constructor() { @@ -23,18 +23,18 @@ class QuestionView extends Component { getQuestions = () => { $.ajax({ url: `/questions?page=${this.state.page}`, //TODO: update request URL - type: 'GET', + type: "GET", success: (result) => { this.setState({ questions: result.questions, totalQuestions: result.total_questions, categories: result.categories, - currentCategory: result.current_category, + // currentCategory: result.current_category, }); return; }, error: (error) => { - alert('Unable to load questions. Please try your request again'); + alert("Unable to load questions. Please try your request again"); return; }, }); @@ -51,7 +51,7 @@ class QuestionView extends Component { pageNumbers.push( { this.selectPage(i); }} @@ -66,7 +66,7 @@ class QuestionView extends Component { getByCategory = (id) => { $.ajax({ url: `/categories/${id}/questions`, //TODO: update request URL - type: 'GET', + type: "GET", success: (result) => { this.setState({ questions: result.questions, @@ -76,7 +76,7 @@ class QuestionView extends Component { return; }, error: (error) => { - alert('Unable to load questions. Please try your request again'); + alert("Unable to load questions. Please try your request again"); return; }, }); @@ -85,9 +85,9 @@ class QuestionView extends Component { submitSearch = (searchTerm) => { $.ajax({ url: `/questions`, //TODO: update request URL - type: 'POST', - dataType: 'json', - contentType: 'application/json', + type: "POST", + dataType: "json", + contentType: "application/json", data: JSON.stringify({ searchTerm: searchTerm }), xhrFields: { withCredentials: true, @@ -102,23 +102,23 @@ class QuestionView extends Component { return; }, error: (error) => { - alert('Unable to load questions. Please try your request again'); + alert("Unable to load questions. Please try your request again"); return; }, }); }; questionAction = (id) => (action) => { - if (action === 'DELETE') { - if (window.confirm('are you sure you want to delete the question?')) { + if (action === "DELETE") { + if (window.confirm("are you sure you want to delete the question?")) { $.ajax({ url: `/questions/${id}`, //TODO: update request URL - type: 'DELETE', + type: "DELETE", success: (result) => { this.getQuestions(); }, error: (error) => { - alert('Unable to load questions. Please try your request again'); + alert("Unable to load questions. Please try your request again"); return; }, }); @@ -128,8 +128,8 @@ class QuestionView extends Component { render() { return ( -
-
+
+

{ this.getQuestions(); @@ -147,7 +147,7 @@ class QuestionView extends Component { > {this.state.categories[id]} {`${this.state.categories[id].toLowerCase()}`} @@ -156,7 +156,7 @@ class QuestionView extends Component {

-
+

Questions

{this.state.questions.map((q, ind) => ( ))} -
{this.createPagination()}
+
{this.createPagination()}
);