Code Monkey home page Code Monkey logo

github-flask's Introduction

GitHub-Flask

GitHub-Flask is an extension for authenticating Flask applications with GitHub. It also provides support for various other requests to the GitHub API. Compatible with Python 2.7 and 3.4.

image

Installation

GitHub-Flask is available on PyPI:

Usage

An example application is provided. Getting it up and running should be pretty straightforward. Edit example.py and change GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET settings. Then run the sample application to see how it's working:

github-flask's People

Contributors

azalloom avatar cenkalti avatar farin avatar ftomassetti avatar greyli avatar jeancarlozapata avatar jezdez avatar lize avatar methane avatar paulrademacher avatar ponteineptique avatar pr0ps avatar rhblind avatar samvarankashyap avatar vassudanagunta avatar woodb avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

github-flask's Issues

Look for configs in os.environ

Would be a nice touch to have the app look in the os.environ if app.config doesn't have the client id and and client secret values.

Similar to how FLASK_DEBUG works. I can do the PRโ€”I wanted to open the issue to check if it's in line with how you see this library being used.

Doesn't work with Blueprints

blueprint = Blueprint('oauth', __name__)
# setup github-flask
github = GitHub(blueprint)

results in

Traceback (most recent call last):
...
  File "/Users/luckydonald/code/more_code/code/yes_code/github_oauth.py", line 14, in <module>
    github = GitHub(blueprint)
  File "/Users/luckydonald/code/virtualenv3.6.venv/lib/python3.6/site-packages/flask_github.py", line 81, in __init__
    self.init_app(self.app)
  File "/Users/luckydonald/code/virtualenv3.6.venv/lib/python3.6/site-packages/flask_github.py", line 86, in init_app
    self.client_id = app.config['GITHUB_CLIENT_ID']
AttributeError: 'Blueprint' object has no attribute 'config'

json content detection is broken

function is_json_response check if content type is equal to "application/json", in my request the json content type is "application/json; charset=utf-8".
would it be better to check if content-type.startwith('application/json') instead of content-type=='application/json'

edit: this is fixed by #23

Example database just keeps on growing

The database keeps growing as new session tokens are added and never removed. Is this as expected or should there be a mechanism to timeout/expire/remove old tokens?

Add conditional request support

The github recommends conditional requests:

Most responses return an ETag header. Many responses also return a Last-Modified header. You can use the values of these headers to make subsequent requests to those resources using the If-None-Match and If-Modified-Since headers, respectively. If the resource has not changed, the server will return a 304 Not Modified. Also note: making a conditional request and receiving a 304 response does not count against your Rate Limit, so we encourage you to use it whenever possible.

Can we add this support to receive 304s?

Sleep mechanism for github ban

When I was using github-flask to crawl all the fork list of one repo on multi-thread:
request('GET', 'repos/%s/forks' % project_name, True)

It wil be ban by github.

image

Is there any way I can avoid this if I use all_pages=True in
request(method, resource, all_pages=False, **kwargs) ?

My idea is that give user a option for not crawling so fast, like sleep(1) after each API call.

Unable to set headers on github.post method

I have been trying to set a hook for my organization, and because the related API methods are still in alpha, an 'Accept' header is needed.

When I:

        hook_registration = {
            'name': 'web',
            'active': True,
            'events': ['push', 'pull_request'],
            'config': {
                'url': 'http://example.com/webhook',
                'content_type': 'json'
            }
        }
        return github.post('/orgs/%s/hooks' % org,
                           data=hook_registration,
                           headers={'Accept': 'application/vnd.github.sersi-preview+json'})

I get an error:

   ...
    File "/home/rhlobo/.virtualenvs/jackdaw/lib/python2.7/site-packages/flask_github.py", line 191, in post
data=data, **kwargs)
   TypeError: request() got multiple values for keyword argument 'headers'

About pagination of github.get

@cenkalti Sounds great example! Do you have API reference document with detailed introduction about flask_github.GitHub.get ? As you know it only returns 30 records by default in first page, trying to leverage this method for all pagination records instead to write own.

Auth decorator cannot resolve github.com

My code is the same as your example.

It seems the decorator cannot call the access_token endpoint with the code parameter to get the token, but it could successfully get to the callback...

screenshot-192 168 99 100 5555 2015-11-24 16-50-11

Add mocking capability

I have an app that uses this extension and I want to mock the login function for testing. I was thinking that maybe we could add a a flag saying that the app is in test mode or not, if that is the case, then mock everything. I am willing to implement this :)

github_access_token should be String not Integer

sqlalchemy.exc.DataError
DataError: (DataError) invalid input syntax for integer: "edd8631feac9c67eb3b65dab93c111243b4ccef7"
LINE 3: WHERE users.github_access_token = 'edd8631feac9c67eb3b65dab9...
                                          ^
 'SELECT users.id AS users_id, users.username AS users_username, users.github_access_token AS users_github_access_token \nFROM users \nWHERE users.github_access_token = %(github_access_token_1)s \n LIMIT %(param_1)s' {'param_1': 1, 'github_access_token_1': u'edd8631geac9c67eb3b65dab93c111143b4ccee1'}

The /user route in example.py gives me 401 Bad Credentials.

So I ran the example.py as per the docs. I am able to authenticate with my app but I don't think it is saving the logged in user. So when I go to /user after the authentication, it gives me flask_github.GitHubError: 401: Bad credentials

Do I need to save g.user somewhere? What is the purpose of that /user route?

unsupported operand type(s) for +=: 'dict' and 'dict'

The Search API provides a multi-page search, but returns dicts (and not lists), leading to an error. That's the only multi-page dict I've found in the API.

A quick fix would be to use something like that in request:

body = response.json()
if isinstance(body, list):
    result += body
elif isinstance(body, dict) and 'items' in body:
    result['items'] += body['items']

Any better ideas?

Get requests does not pass on query parameters

Hi,

In the get() shortcut method, the params kwarg is not passed on to the self.request metod.

Is this by design?

When doing a query like this, I'd expect my parameters to be passed on to the Github API.

    def get(self):
        repo_dict = github.get('user/repos', params={'type': 'private'})
        return repo_dict

This way I should only receive my private repositories

TypeError: __name__ must be set to a string object

Here is the problem:

The current environment is py2.7 , and i wanna write code capable of python3. So i add "from future import unicode_literals" on the top of file.Meanwhile, i use MethodView to build rest api in the same file.
However, when i run the web app, it thows the error,

"lib/python2.7/site-packages/flask/views.py", line 102, in as_view
view.__name__ = name
TypeError: __name__ must be set to a string object". 

I soon realize that because i use the "from future import unicode_literals" in py2 so the function name is unicode type, but the name of a function should be string type.So i wonder could we change the
source code and add the if-then workflow to convert name of function from unicode type into string type to handle the situation .

Naming convention for project

This may be a bit meta, but most Flask extensions out there follow the naming convention of flask-extensionname.

Not trying to be overly dogmatic, but it might fit the spirit of the project better to be named flask-github instead...

Migrate to request headers for token authentication

It looks like certain parts of the GitHub API don't support the access_token query parameter.

I don't think this is entirely documented, but I noticed that when working with the GitHub deployments API that the access_token query parameter was not working (perhaps a fluke in what is one of the relatively newer components to the GitHub API).

I found that by manually passing the Authorization header to the post method that my requests began to work again.

I propose switching to use the Authorization header rather than the access_token query parameter (or why not both).

How to use github-flask for registration and authentication

I would like to use github-flask for registering new users and for authenticating them. However I do not know how I could distinguish such cases because the callback URI seems to be just one and I do not see how to pass to authorize parameters to distinguish the two cases

API call return 404 error

When I call github.get('/user') in my code, I got GitHubError: 404: Not Found.

Here is the code, the authorization part is good.

@auth.route('/login/github')
def github_login():
    return github.authorize(scope="user")

@github.access_token_getter
def token_getter():
    if current_user.is_authenticated:
        return current_user.access_token

@auth.route('/callback/github')
@github.authorized_handler
def authorized(access_token):
    next_url = request.args.get('next') or url_for('chat.app')
    if access_token is None:
        return redirect(next_url)

    user = User.query.filter_by(access_token=access_token).first()
    if user is None:
        user = User(access_token=access_token)
        user.save()
        login_user(user)
        github_user = github.get('/user')  # the error line
        print github_user
        return redirect(url_for('chat.profile'))
        
    user.access_token = access_token
    user.save()
    login_user(user)

    return redirect(next_url)

The API endpoint is listed in here.

Did I do something wrong? Any help will be appreciated.

passing callback url to authorize

Hi, in the docs there is:

def authorized_handler(self, f):
        """
        Decorator for the route that is used as the callback for authorizing
        with GitHub. This callback URL can be set in the settings for the app
        or passed in during authorization.

        """

https://github.com/cenkalti/github-flask/blob/master/flask_github.py#L98

But there is no such parameter in authorize

def authorize(self, scope=None):
        """
        Redirect to GitHub and request access to a user's data.

        """

https://github.com/cenkalti/github-flask/blob/master/flask_github.py#L77

How can I pass the callback url during the authorization?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.