librelist archives

« back to archive

posting to a flask-restless api endpoint from a view

posting to a flask-restless api endpoint from a view

From:
Reuben Cummings
Date:
2013-01-23 @ 17:35
Hi, I am trying to convert my app from posting form contents to the db
using the model classes, to using the flask-restless api endpoints. I
have gotten it to work with flask-script but when I try to post within
a view it hangs. My dir layout is as follows:

application/
|--manage.py
|--app/
     |--__init__.py
     |--models.py
     |--views.py
     |--app.db

And I have the following extensions:
- flask.ext.sqlalchemy
- flask.ext.restless
- flask.ext.script


********************
*** manage.py ***
********************
#!/usr/bin/env python
import os.path as p

from flask import current_app as app
from flask.ext.script import Manager
from app import create_app, db, api_post

manager = Manager(create_app)


@manager.command
def initdb():
	with app.app_context():
		db.drop_all()
		db.create_all()
		api_post({'symbol': 'init', 'name': 'manage', 'value': 100})
		print 'Database initialized'


if __name__ == '__main__':
	manager.run()


********************
*** __init__.py ***
********************
from os import path as p
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.restless import APIManager

from json import dumps as dmp
from requests import post

db = SQLAlchemy()
site = 'http://localhost:5000/api'
hdr = {'content-type': 'application/json'}


def api_post(d):
	r = post('http://localhost:5000/api/exchange', data=dmp(d), headers=HDR)
	return r


def create_app():
	app = Flask(__name__)
	app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///%s' % p.join(
		p.dirname(__file__), 'app.db')
	app.config['DEBUG'] = True
	app.config['API_METHODS'] = ['GET', 'POST']

	db.init_app(app)
	app.register_blueprint(appview)
	mgr = APIManager(app, flask_sqlalchemy_db=db)
	mgr.create_api(Exchange, methods=app.config['API_METHODS'])
	return app

from .views import appview
from .models import Exchange

********************
***  models.py ***
********************
from app import db


class Exchange(db.Model):
	id = db.Column(db.Integer, primary_key=True)
	symbol = db.Column(db.String(12), nullable=False)
	name = db.Column(db.String(64), nullable=False)
	value = db.Column(db.Float)

********************
***   views.py   ***
********************
from flask import Blueprint, redirect
from app import api_post

appview = Blueprint('appview', __name__)


@appview.route('/pop/', methods=['GET', 'POST'])
def pop():
	r = api_post({'symbol': 'pop', 'name': 'view', 'value': 200})
	return redirect('/api/exchange')


Then, from the command line...

./manage.py runserver
./manage.py initdb

Go to http://localhost:5000/api/exchange and you get the following

{
  "total_pages": 1,
  "objects": [
    {
      "symbol": "init",
      "id": 1,
      "value": 100.0,
      "name": "manage"
    }
  ],
  "num_results": 1,
  "page": 1
}

But go to http://localhost:5000/pop and nothing happens. And if I
comment out the line

    r = api_post({'symbol': 'pop', 'name': 'view', 'value': 200})

from pop(), it redirects fine.

However, from the flask-script shell...

./manage.py shell
>>> from app.views import pop
>>> pop()
<BaseResponse 233 bytes [302 FOUND]>

Now revisit http://localhost:5000/api/exchange and you will see

{
  "total_pages": 1,
  "objects": [
    {
      "symbol": "init",
      "id": 1,
      "value": 100.0,
      "name": "manage"
    },
    {
      "symbol": "pop",
      "id": 2,
      "value": 200.0,
      "name": "view"
    }
  ],
  "num_results": 2,
  "page": 1
}

Does anyone know why the view just hangs in the browser?

-- 


Reuben Cummings

posting to a flask-restless api endpoint from a view

From:
Reuben Cummings
Date:
2013-01-24 @ 23:21
Hi, I am trying to convert my app from posting form contents to the db
using the model classes, to using the flask-restless api endpoints. I
have gotten it to work with flask-script but when I try to post within
a view it hangs. My dir layout is as follows:

application/
|--manage.py
|--app/
     |--__init__.py
     |--models.py
     |--views.py
     |--app.db

And I have the following extensions:
- flask.ext.sqlalchemy
- flask.ext.restless
- flask.ext.script


********************
*** manage.py ***
********************
#!/usr/bin/env python
import os.path as p

from flask import current_app as app
from flask.ext.script import Manager
from app import create_app, db, api_post

manager = Manager(create_app)


@manager.command
def initdb():
	with app.app_context():
		db.drop_all()
		db.create_all()
		api_post({'symbol': 'init', 'name': 'manage', 'value': 100})
		print 'Database initialized'


if __name__ == '__main__':
	manager.run()


********************
*** __init__.py ***
********************
from os import path as p
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.restless import APIManager

from json import dumps as dmp
from requests import post

db = SQLAlchemy()
site = 'http://localhost:5000/api'
hdr = {'content-type': 'application/json'}


def api_post(d):
	r = post('http://localhost:5000/api/exchange', data=dmp(d), headers=HDR)
	return r


def create_app():
	app = Flask(__name__)
	app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///%s' % p.join(
		p.dirname(__file__), 'app.db')
	app.config['DEBUG'] = True
	app.config['API_METHODS'] = ['GET', 'POST']

	db.init_app(app)
	app.register_blueprint(appview)
	mgr = APIManager(app, flask_sqlalchemy_db=db)
	mgr.create_api(Exchange, methods=app.config['API_METHODS'])
	return app

from .views import appview
from .models import Exchange

********************
***  models.py ***
********************
from app import db


class Exchange(db.Model):
	id = db.Column(db.Integer, primary_key=True)
	symbol = db.Column(db.String(12), nullable=False)
	name = db.Column(db.String(64), nullable=False)
	value = db.Column(db.Float)

********************
***   views.py   ***
********************
from flask import Blueprint, redirect
from app import api_post

appview = Blueprint('appview', __name__)


@appview.route('/pop/', methods=['GET', 'POST'])
def pop():
	r = api_post({'symbol': 'pop', 'name': 'view', 'value': 200})
	return redirect('/api/exchange')


Then, from the command line...

./manage.py runserver
./manage.py initdb

Go to http://localhost:5000/api/exchange and you get the following

{
  "total_pages": 1,
  "objects": [
    {
      "symbol": "init",
      "id": 1,
      "value": 100.0,
      "name": "manage"
    }
  ],
  "num_results": 1,
  "page": 1
}

But go to http://localhost:5000/pop and nothing happens. And if I
comment out the line

    r = api_post({'symbol': 'pop', 'name': 'view', 'value': 200})

from pop(), it redirects fine.

However, from the flask-script shell...

./manage.py shell
>>> from app.views import pop
>>> pop()
<BaseResponse 233 bytes [302 FOUND]>

Now revisit http://localhost:5000/api/exchange and you will see

{
  "total_pages": 1,
  "objects": [
    {
      "symbol": "init",
      "id": 1,
      "value": 100.0,
      "name": "manage"
    },
    {
      "symbol": "pop",
      "id": 2,
      "value": 200.0,
      "name": "view"
    }
  ],
  "num_results": 2,
  "page": 1
}

Does anyone know why the view just hangs in the browser?

-- 


Reuben Cummings