Skip to content
Snippets Groups Projects
Commit bc96133c authored by zshan2's avatar zshan2
Browse files

assignment-2.2 ver2.0 CSS style added, creating form input

parent ca7b5d83
Branches master
No related tags found
1 merge request!2Implementation of assignment-2.2
......@@ -98,9 +98,6 @@ def get_documents_json(opt, identifier):
for item in data:
item.pop("_id")
file[typeName].append(item)
print("===============================================")
print(file)
print("===============================================")
return json.dumps(file)
......
......@@ -77,6 +77,8 @@ def parse_query_to_json(pair):
else:
return {elements[0].split(".")[1]: {"$regex": elements[1], "$options": "i"}}
else:
if len(elements[0].split(".")) != 2:
return {"wrong": "True"}
if re.search(">", pair):
return {elements[0].split(".")[1]: {"$gt": float(elements[1])}}
elif re.search("<", pair):
......
......@@ -7,8 +7,10 @@ from flask import request
from flask import abort
from flask import jsonify
from urllib.parse import urlparse, parse_qs
from flask_cors import CORS
app = Flask(__name__)
cors = CORS(app)
# app.config["DEBUG"] = True
......@@ -26,22 +28,33 @@ def data_base(collection):
url_parsed = urlparse(request.url)
qs_parsed = parse_qs(url_parsed.query)
if qs_parsed == {}:
return jsonify(DataBase.get_documents_json(0, {}))
return jsonify(search_document(["book.id:" + qs_parsed["id"][0]]))
return DataBase.get_documents_json(0, {})
result = search_document(["book.id:" + qs_parsed["id"][0]])
if result == {"wrong": "True"}:
abort(400, "Bad Request")
else:
return result
elif collection == "author":
url_parsed = urlparse(request.url)
qs_parsed = parse_qs(url_parsed.query)
if qs_parsed == {}:
return jsonify(DataBase.get_documents_json(1, {}))
return jsonify(search_document(["author.id:" + qs_parsed["id"][0]]))
return DataBase.get_documents_json(1, {})
result = search_document(["author.id:" + qs_parsed["id"][0]])
if result == {"wrong": "True"}:
abort(400, "Bad Request")
else:
return result
elif collection == "search":
url_parsed = urlparse(request.url)
query = Parser.parse_url_to_query(url_parsed.query)
qs_parsed = query.replace("q=", "")
result = search_document(qs_parsed.split("&"))
return result
if result == {"wrong": "True"}:
abort(400, "Bad Request")
else:
return result
else:
abort(404)
abort(400, "Bad Request")
elif request.method == "PUT":
if request.headers["Content-Type"] != "application/json":
abort(415)
......@@ -51,7 +64,7 @@ def data_base(collection):
elif collection == "author":
opt = 1
else:
abort(400)
abort(400, "Bad Request")
DataBase.update_dicts(opt, request.args.to_dict(), json_update_info)
return "200: PUT succeeded"
elif request.method == "POST":
......@@ -74,7 +87,7 @@ def data_base(collection):
Scrape.scrape_api(url, max_book, max_author)
return "200: new data has been added to database"
else:
abort(400)
abort(400, "Bad Request")
return "200: POST succeeded"
elif request.method == "DELETE":
identifier = request.args.to_dict()
......@@ -93,6 +106,8 @@ def search_document(identifiers):
""" function used to find one or several document in database """
if len(identifiers) == 1:
json_idt = Parser.parse_query_to_json(identifiers[0])
if json_idt == {"wrong": "True"}:
return {"wrong": "True"}
print(json_idt)
if re.search("^book.*", identifiers[0]):
return DataBase.get_documents_json(0, json_idt)
......@@ -113,6 +128,8 @@ def search_document(identifiers):
opt = 1
json_idt1 = Parser.parse_query_to_json(identifiers[0])
json_idt2 = Parser.parse_query_to_json(identifiers[2])
if json_idt1 == {"wrong": "True"} or json_idt2 == {"wrong": "True"}:
return {"wrong": "True"}
if identifiers[1] == "AND":
exp = {"$and": [json_idt1, json_idt2]}
elif identifiers[1] == "OR":
......@@ -124,7 +141,8 @@ def search_document(identifiers):
print(exp)
return DataBase.get_documents_json(opt, exp)
else:
return "Error, unknown identifiers"
print("Error, unknown identifiers")
return {}
if __name__ == "__main__":
......
......@@ -38,13 +38,13 @@ class DataBaseTests(unittest.TestCase):
url = "http://127.0.0.1:5000/api/book?id=12345678"
res = requests.get(url)
self.assertEqual(res.status_code, 200)
self.assertEqual(res.json(), "{'books': []}")
self.assertEqual(res.json(), {'books': []})
def test_invalid_get_wrong_collection_name(self):
db.insert_document(self.test_data1, 0)
url = "http://127.0.0.1:5000/api/bookssss?id=38746485"
res = requests.get(url)
self.assertEqual(res.status_code, 404)
self.assertEqual(res.status_code, 400)
def test_valid_put(self):
db.insert_document(self.test_data1, 0)
......
......@@ -25,59 +25,139 @@
//export default App;
import React, { useState } from 'react';
import FourButtons from './Components/FourButtons'
import FourButtons from './Components/FourButtons';
import { Dialog } from 'react-overlay-pack';
import CorrectSign from './material/sign_correct.png';
import ErrorSign from './material/sign_error.png';
function App() {
const { useState } = React;
const [queryStr, setQueryStr] = useState('')
const [jsonValue, setJsonValue] = useState('')
const [sign, setSign] = useState(CorrectSign)
const [text, setText] = useState('This area shows the result of requests..')
const [formState, setFormState] = useState('hide')
const [dialogState, setDialogState] = useState(false)
const axios = require('axios').default;
var center = {display: 'flex', justifyContent: 'center', alignItems: 'center'}
function get() {
axios.get('http://127.0.0.1:5000/api/' + queryStr)
.then(function (response) {
// handle success
setSign(CorrectSign)
showDialog()
document.getElementById('dialog').value = response.status + ":\n" + response.statusText
document.getElementById('board').value = JSON.stringify(response.data)
})
.catch(function (error) {
// handle error
setSign(ErrorSign)
showDialog()
document.getElementById('dialog').value = error
})
}
function put() {
changeFormState()
}
function mesg() {
alert('Hey!')
document.getElementById('board').value = 'Hello there!'
}
function changeFormState() {
if (formState === 'hide') {
setFormState('show')
} else {
setFormState('hide')
}
}
function showDialog() {
setDialogState(true)
}
return (
<div>
{dialogState === true &&
<Dialog
show={dialogState}
onOutsideClick={() => setDialogState(false)}>
<div style={{marginTop:'20%'}}>
<div style={{
marginLeft: '35%'
}}>
<img src={sign}/>
</div>
<div>
<textarea id='dialog'
readOnly={true}
rows="3"
cols="38"
style={{
border:'2px solid silver',
backgroundColor: 'white',
fontSize: '200%',
margin: '50px'
}}>
{text}
</textarea>
</div>
</div>
</Dialog>}
<form name='mainform'>
<h1> Welcome to the home page of GoodReads Crawler! </h1>
<h3> Please input your query string:</h3>
<input
id='queryString'
type='text'
placeholder='example: book?id=12345678'
size='40'
value={queryStr}
onChange={(e) => setQueryStr(e.target.value)}
/>
<h3> Please input your json parameters (only effective for POST and PUT):</h3>
<input
id='jsonValue'
type='text'
placeholder='example: {"rating_counr": 1000000}'
size='40'
value={jsonValue}
onChange={(e) => setJsonValue(e.target.value)}
/>
<h1 style={center}>
Welcome to the home page of GoodReads Crawler! </h1>
<h3 style={center}> Please input your query string:</h3>
<div style={center}>
<input
id='queryString'
type='text'
placeholder='example: book?id=12345678'
size='40'
value={queryStr}
onChange={(e) => setQueryStr(e.target.value)}
/>
</div>
<h3 style={center}> Please input your data for uploading (only effective for POST and PUT):</h3>
{formState === 'hide' &&
<div style={center}>
<button style={{width:60}} onClick={changeFormState}>
book
</button>
<button style={{marginLeft:10, width:60}} onClick={changeFormState}>
author
</button>
</div>}
{formState === 'show' &&
<form style={center}>
<table border="1" style="width:100%;">
<tr>
<td>Cell 1</td>
<input/>
</tr>
<tr>
<td>Cell 3</td>
<input/>
</tr>
</table>
</form>}
</form>
<div style={{marginTop:20}}>
<div style={{marginTop:20, display: 'flex', justifyContent: 'center', alignItems: 'center'}}>
<FourButtons
backColor='blue'
borderColor='RoyalBlue'
leftMargin={0}
text='GET'
func={mesg} />
func={get} />
<FourButtons
backColor='black'
borderColor='gray'
leftMargin={20}
text='PUT'
func={mesg} />
func={put} />
<FourButtons
backColor='green'
borderColor='seagreen'
leftMargin={20}
text='POST'
func={mesg} />
func={showDialog} />
<FourButtons
backColor='red'
borderColor='indianred'
......@@ -85,7 +165,7 @@ function App() {
text='DELETE'
func={mesg} />
</div>
<div style={{marginTop:20}}>
<div style={{marginTop:20, display: 'flex', justifyContent: 'center', alignItems: 'center'}}>
<textarea id="board" name="returnData" rows="6" cols="50" value={text} readOnly={true}>
</textarea>
</div>
......
web/app/src/material/sign_correct.png

8.5 KiB

web/app/src/material/sign_error.png

9.39 KiB

0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment