Skip to content

Commit ff183af

Browse files
authored
Merge pull request #1 from ChinhQuoc/feature/1-init-project
feature/1-init-project
2 parents 7d64e39 + c63307e commit ff183af

File tree

4 files changed

+78
-26
lines changed

4 files changed

+78
-26
lines changed

backend/app.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import os
2+
from flaskr import create_app
3+
4+
os.environ['FLASK_APP'] = 'flaskr:create_app'
5+
os.environ['FLASK_ENV'] = 'development'
6+
7+
app = create_app()
8+
9+
if __name__ == '__main__':
10+
app.run()

backend/flaskr/__init__.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,17 +21,39 @@ def create_app(test_config=None):
2121
"""
2222
@TODO: Set up CORS. Allow '*' for origins. Delete the sample route after completing the TODOs
2323
"""
24+
#CORS(app, resources={r"*/api/*" : {origins: '*'}})
25+
26+
CORS(app)
2427

2528
"""
2629
@TODO: Use the after_request decorator to set Access-Control-Allow
2730
"""
31+
@app.after_request
32+
def after_request(response):
33+
response.headers.add('Access-Control-Allow-Headers', 'Content-Type, Authorization')
34+
response.headers.add('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE, OPTIONS')
35+
return response
2836

2937
"""
3038
@TODO:
3139
Create an endpoint to handle GET requests
3240
for all available categories.
3341
"""
42+
@app.route('/categories')
43+
def get_categories():
44+
# Implement pagination
45+
page = request.args.get('page', 1, type=int)
46+
start = (page - 1) * 10
47+
end = start + 10
48+
49+
categories = Category.query.all()
50+
formatted_categories = [category.format() for category in categories]
3451

52+
return jsonify({
53+
'success': True,
54+
'categories': formatted_categories[start:end],
55+
'total_categories': len(formatted_categories)
56+
})
3557

3658
"""
3759
@TODO:
@@ -45,6 +67,25 @@ def create_app(test_config=None):
4567
ten questions per page and pagination at the bottom of the screen for three pages.
4668
Clicking on the page numbers should update the questions.
4769
"""
70+
@app.route('/questions')
71+
def get_questions():
72+
# Implement pagination
73+
page = request.args.get('page', 1, type=int)
74+
start = (page - 1) * 10
75+
end = start + 10
76+
77+
categories = Category.query.all()
78+
formatted_categories = [category.format() for category in categories]
79+
80+
questions = Question.query.all()
81+
formatted_questions = [question.format() for question in questions]
82+
83+
return jsonify({
84+
'success': True,
85+
'questions': formatted_questions[start:end],
86+
'total_questions': len(formatted_questions),
87+
'categories': formatted_categories,
88+
})
4889

4990
"""
5091
@TODO:

backend/models.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import json
55

66
database_name = 'trivia'
7-
database_path = 'postgresql://{}/{}'.format('localhost:5432', database_name)
7+
database_path = 'postgresql://postgres:12345@{}/{}'.format('localhost:5432', database_name)
88

99
db = SQLAlchemy()
1010

@@ -17,7 +17,8 @@ def setup_db(app, database_path=database_path):
1717
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
1818
db.app = app
1919
db.init_app(app)
20-
db.create_all()
20+
with app.app_context():
21+
db.create_all()
2122

2223
"""
2324
Question

frontend/src/components/QuestionView.js

Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
import React, { Component } from 'react';
2-
import '../stylesheets/App.css';
3-
import Question from './Question';
4-
import Search from './Search';
5-
import $ from 'jquery';
1+
import React, { Component } from "react";
2+
import "../stylesheets/App.css";
3+
import Question from "./Question";
4+
import Search from "./Search";
5+
import $ from "jquery";
66

77
class QuestionView extends Component {
88
constructor() {
@@ -23,18 +23,18 @@ class QuestionView extends Component {
2323
getQuestions = () => {
2424
$.ajax({
2525
url: `/questions?page=${this.state.page}`, //TODO: update request URL
26-
type: 'GET',
26+
type: "GET",
2727
success: (result) => {
2828
this.setState({
2929
questions: result.questions,
3030
totalQuestions: result.total_questions,
3131
categories: result.categories,
32-
currentCategory: result.current_category,
32+
// currentCategory: result.current_category,
3333
});
3434
return;
3535
},
3636
error: (error) => {
37-
alert('Unable to load questions. Please try your request again');
37+
alert("Unable to load questions. Please try your request again");
3838
return;
3939
},
4040
});
@@ -51,7 +51,7 @@ class QuestionView extends Component {
5151
pageNumbers.push(
5252
<span
5353
key={i}
54-
className={`page-num ${i === this.state.page ? 'active' : ''}`}
54+
className={`page-num ${i === this.state.page ? "active" : ""}`}
5555
onClick={() => {
5656
this.selectPage(i);
5757
}}
@@ -66,7 +66,7 @@ class QuestionView extends Component {
6666
getByCategory = (id) => {
6767
$.ajax({
6868
url: `/categories/${id}/questions`, //TODO: update request URL
69-
type: 'GET',
69+
type: "GET",
7070
success: (result) => {
7171
this.setState({
7272
questions: result.questions,
@@ -76,7 +76,7 @@ class QuestionView extends Component {
7676
return;
7777
},
7878
error: (error) => {
79-
alert('Unable to load questions. Please try your request again');
79+
alert("Unable to load questions. Please try your request again");
8080
return;
8181
},
8282
});
@@ -85,9 +85,9 @@ class QuestionView extends Component {
8585
submitSearch = (searchTerm) => {
8686
$.ajax({
8787
url: `/questions`, //TODO: update request URL
88-
type: 'POST',
89-
dataType: 'json',
90-
contentType: 'application/json',
88+
type: "POST",
89+
dataType: "json",
90+
contentType: "application/json",
9191
data: JSON.stringify({ searchTerm: searchTerm }),
9292
xhrFields: {
9393
withCredentials: true,
@@ -102,23 +102,23 @@ class QuestionView extends Component {
102102
return;
103103
},
104104
error: (error) => {
105-
alert('Unable to load questions. Please try your request again');
105+
alert("Unable to load questions. Please try your request again");
106106
return;
107107
},
108108
});
109109
};
110110

111111
questionAction = (id) => (action) => {
112-
if (action === 'DELETE') {
113-
if (window.confirm('are you sure you want to delete the question?')) {
112+
if (action === "DELETE") {
113+
if (window.confirm("are you sure you want to delete the question?")) {
114114
$.ajax({
115115
url: `/questions/${id}`, //TODO: update request URL
116-
type: 'DELETE',
116+
type: "DELETE",
117117
success: (result) => {
118118
this.getQuestions();
119119
},
120120
error: (error) => {
121-
alert('Unable to load questions. Please try your request again');
121+
alert("Unable to load questions. Please try your request again");
122122
return;
123123
},
124124
});
@@ -128,8 +128,8 @@ class QuestionView extends Component {
128128

129129
render() {
130130
return (
131-
<div className='question-view'>
132-
<div className='categories-list'>
131+
<div className="question-view">
132+
<div className="categories-list">
133133
<h2
134134
onClick={() => {
135135
this.getQuestions();
@@ -147,7 +147,7 @@ class QuestionView extends Component {
147147
>
148148
{this.state.categories[id]}
149149
<img
150-
className='category'
150+
className="category"
151151
alt={`${this.state.categories[id].toLowerCase()}`}
152152
src={`${this.state.categories[id].toLowerCase()}.svg`}
153153
/>
@@ -156,7 +156,7 @@ class QuestionView extends Component {
156156
</ul>
157157
<Search submitSearch={this.submitSearch} />
158158
</div>
159-
<div className='questions-list'>
159+
<div className="questions-list">
160160
<h2>Questions</h2>
161161
{this.state.questions.map((q, ind) => (
162162
<Question
@@ -168,7 +168,7 @@ class QuestionView extends Component {
168168
questionAction={this.questionAction(q.id)}
169169
/>
170170
))}
171-
<div className='pagination-menu'>{this.createPagination()}</div>
171+
<div className="pagination-menu">{this.createPagination()}</div>
172172
</div>
173173
</div>
174174
);

0 commit comments

Comments
 (0)