implemented list view for posts

master
Malar Kannan 2017-08-10 01:46:22 +05:30
parent 617f6b890e
commit d5d980a25d
8 changed files with 105 additions and 30 deletions

View File

@ -24,7 +24,8 @@ class ProductionConfig(Config):
DATABASE_URI = 'mysql://user@localhost/foo'
class DevelopmentConfig(Config):
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
# SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/typeset.db'
DEBUG = True
class TestingConfig(Config):

View File

@ -5,18 +5,20 @@ Licence: GPLv3
"""
from app import db
from uuid import uuid4
from datetime import datetime
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
id = db.Column(db.String(32), primary_key=True)
title = db.Column(db.String(80))
pub_date = db.Column(db.DateTime)
def __init__(self, title,paragraphs, pub_date=None):
def __init__(self, title, pub_date=None):
self.title = title
if pub_date is None:
pub_date = datetime.utcnow()
self.pub_date = pub_date
self.paragraphs = paragraphs
self.id = uuid4().hex
def __repr__(self):
return '<Post %r>' % self.title
@ -24,8 +26,8 @@ class Post(db.Model):
class Paragraph(db.Model):
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.Text)
post_id = db.Column(db.Integer, db.ForeignKey('post.id'))
db.relationship('Post',backref=db.backref('paragraphs', lazy='dynamic'))
post_id = db.Column(db.String(32), db.ForeignKey('post.id'))
post = db.relationship('Post',backref=db.backref('paragraphs', lazy='dynamic'))
def __init__(self, body,post_id):
self.body = body
@ -39,8 +41,8 @@ class Comment(db.Model):
name = db.Column(db.String(50))
message = db.Column(db.String(140))
paragraph_id = db.Column(db.Integer, db.ForeignKey('paragraph.id'))
post_id = db.Column(db.Integer, db.ForeignKey('post.id'))
db.relationship('Paragraph',backref=db.backref('comments', lazy='dynamic'))
post_id = db.Column(db.String(32), db.ForeignKey('post.id'))
paragraph = db.relationship('Paragraph',backref=db.backref('comments', lazy='dynamic'))
def __init__(self, name,message):
self.name = name

View File

@ -6,7 +6,8 @@ Licence: GPLv3
from flask import request
from flask_restless import APIManager
from flask_restful import Resource,Api
from flask_restplus import Resource,Api
import json
from app import app,db
from models import Post,Paragraph,Comment
@ -14,7 +15,7 @@ from models import Post,Paragraph,Comment
manager = APIManager(app, flask_sqlalchemy_db=db)
# Create API endpoints, which will be available at /api/<tablename> by
# default. Allowed HTTP methods can be specified as well.
manager.create_api(Post, methods=['GET'])
manager.create_api(Post, methods=['GET'],results_per_page=5)
manager.create_api(Paragraph, methods=['GET'])
manager.create_api(Comment, methods=['GET','POST'])
@ -27,18 +28,22 @@ def index():
class CreatePost(Resource):
def post(self):
print('hello')
try:
post_data = json.parse(request.data)
post_data = json.loads(request.data)
title = post_data['title']
content = post_data['content']
p = Post(title)
pgs = content.split('\n')
db.session.add(p)
db.session.add(p)
return {'post_id':'title'}
p_e = Post(title)
db.session.add(p_e)
pgs = content.split('\n\n')
for pg in pgs:
pg_e = Paragraph(body=pg,post_id=p_e.id)
db.session.add(pg_e)
db.session.commit()
return {'post_id':p_e.id}
except Exception as e:
return {'error':'invalid_post'}
print(e)
return restapi.abort(400,'Invalid data')
restapi.add_resource(CreatePost,'/api/create_post')
# @app.route('/api/create_post',methods=['POST'])

View File

@ -9,6 +9,7 @@
"@types/react-dom": "^15.5.2",
"@types/react-router": "^4.0.14",
"@types/react-router-dom": "^4.0.7",
"lodash": "^4.17.4",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-router": "^4.1.2",
@ -19,6 +20,7 @@
"yarn": "^0.27.5"
},
"devDependencies": {
"@types/lodash": "^4.14.72",
"app-root-path": "^2.0.1",
"autoprefixer": "7.1.0",
"case-sensitive-paths-webpack-plugin": "2.0.0",

View File

@ -5,8 +5,9 @@ import { Link } from 'react-router-dom';
export class HeaderMenu extends React.Component<any, any> {
state = { activeItem: 'listpost' };
handleItemClick = (e: any, d: any) => this.setState({ activeItem: d.name });
handleItemClick = (e: any, d: any) => {
this.setState({ activeItem: d.name });
}
render() {
let { activeItem } = this.state;
return (

View File

@ -1,10 +1,70 @@
import * as React from 'react';
// import { Comment } from 'semantic-ui-react';
import { Menu, List } from 'semantic-ui-react';
import { HeaderMenu } from './headermenu';
import * as _ from 'lodash';
export class ListPost extends React.Component<any, any> {
render() {
export const PostLinks: React.StatelessComponent<any> = (props) => {
let postItems = props.posts.map((o: any, i: number) => (
<List.Item key={i}>
<List.Icon name="book" size="large" verticalAlign="middle" />
<List.Content>
<List.Header as="a">{o.title}</List.Header>
<List.Description as="a">published at {o.pub_date}</List.Description>
</List.Content>
</List.Item>
));
return (
<List divided={true} relaxed={true}>
{postItems}
</List>
);
};
export class ListPosts extends React.Component<any, any> {
constructor(props: any) {
super(props);
let pageContent = { objects: [], page: 1, total_pages: 1 };
this.state = { pageNo: 1, pageContent };
}
componentDidMount() {
this.getPage(1);
}
public render() {
let handleItemClick = (e: any, d: any) => {
this.getPage(_.toInteger(d.name));
};
let { page, total_pages } = this.state.pageContent;
let items = _.times(total_pages, (n: number) => {
return (
<Menu.Item
key={n}
name={(n + 1).toString()}
active={page === n + 1}
onClick={handleItemClick}
/>
);
});
let { objects } = this.state.pageContent;
return (
null
<HeaderMenu>
<PostLinks posts={objects} />
<Menu pagination={true}>
{items}
</Menu>
</HeaderMenu>
);
}
getPage(pageNo: number) {
fetch('/api/post?page=' + pageNo.toString())
.then((response) => response.text())
.then((responseText) => {
let pageContent = JSON.parse(responseText);
console.log('postlist', pageContent);
this.setState({ pageContent });
})
.catch((err) => {
console.log('some error occurred');
});
}
}

View File

@ -1,15 +1,15 @@
import * as React from 'react';
import { Route, HashRouter } from 'react-router-dom';
import { App } from './app';
import { AddPost } from './components';
// import { App } from './app';
import { AddPost, ListPosts } from './components';
export const AppRouter: React.StatelessComponent<{}> = () => {
return (
<HashRouter>
<HashRouter hashType="slash">
<div >
<Route exact={true} path="/" component={App} />
<Route exact={true} path="/" component={ListPosts} />
<Route path="/addpost" component={AddPost} />
<Route path="/listposts" component={AddPost} />
<Route path="/listposts" component={ListPosts} />
</div>
</HashRouter>
);

View File

@ -17,6 +17,10 @@
version "20.0.6"
resolved "https://registry.yarnpkg.com/@types/jest/-/jest-20.0.6.tgz#7e0ba76ddfacb42ee9bb0d8833e5208cf0680431"
"@types/lodash@^4.14.72":
version "4.14.72"
resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.14.72.tgz#f090cf6eb1fee1647a0efa1ebe18b0b78ed551c6"
"@types/node@*", "@types/node@^8.0.20":
version "8.0.20"
resolved "https://registry.yarnpkg.com/@types/node/-/node-8.0.20.tgz#65c7375255c24b184c215a5d0b63247c32f01c91"
@ -3068,7 +3072,7 @@ lodash.uniq@^4.5.0:
version "4.5.0"
resolved "https://registry.yarnpkg.com/lodash.uniq/-/lodash.uniq-4.5.0.tgz#d0225373aeb652adc1bc82e4945339a842754773"
"lodash@>=3.5 <5", lodash@^4.14.0, lodash@^4.17.2, lodash@^4.17.3, lodash@^4.2.0, lodash@^4.3.0:
"lodash@>=3.5 <5", lodash@^4.14.0, lodash@^4.17.2, lodash@^4.17.3, lodash@^4.17.4, lodash@^4.2.0, lodash@^4.3.0:
version "4.17.4"
resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.4.tgz#78203a4d1c328ae1d86dca6460e369b57f4055ae"