看此篇文章之前请点击这里~了解一些相关知识点~这次我们基于flask mysql redis用Token ,Session&Cookie(存到客户端),Session&Cookie(存到服务端) 做一个登陆验证demo,增加对此的认识~(实践最重要~)


  • 先从Token开始吧~下图是我们这次的流程图~

  • flask准备一个user的Model类,用来保存账号密码~ 其中hash_password方法使用itsdangerous来生成Token,存入redis。
class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(500), index=True)
    password_hash = db.Column(db.String(500))

    def hash_password(self, password):  #加密密码
        self.password_hash = pwd_context.encrypt(password)

    def verify_password(self, password):  #验证密码
        return pwd_context.verify(password, self.password_hash)

    def generate_auth_token(self, expires_in=86400):  #生成token
        s = Serializer(app.config['SECRET_KEY'], expires_in=expires_in)
        return s.dumps({'id':,'username':self.username})
  • 以下为注册函数,获取请求中的username与password,并验证请求中的参数,验证成功后存入数据库~
    @autoApi.route('/user', methods=['POST'])
    def new_user():
        username = request.json.get('username')
        password = request.json.get('password')
        if not username  or not password:
            return jsonify({'status':401,'message':'参数缺失'}),401  
        if User.query.filter_by(username=username).first() is not None:
            return jsonify({'status':400,'message':'用户已存在'}),400 
        user = User(username=username)
        return jsonify({'status':200,'message':'注册成功','username': user.username}),200


  • 打开postman 测试一下~成功注册一个不存在的用户:

  • 此时数据库中存入的密码则为为加密后的:


  • 再次用该账号注册,返回错误信息:


  • 接下来写一个login函数,用来验证请求参数,并生成token,存入redis:(每次登录刷新一个token,之前的token则失效,此方法可做成单处登陆)
    def login():
            username = request.json.get('username')
            password = request.json.get('password')
            obj = User.query.filter_by(username=username).first()
            if not obj:
                return jsonify(201,'',u'未找到该用户')
            if obj.verify_password(password):
                token = obj.generate_auth_token(200).decode('utf-8')
                return jsonify(200,{'token':token},u'登录成功')
                return jsonify(202,'',u'密码错误')
            return jsonify(203, '', u'参数错误')
  • 用刚才注册的用户测试一下~成功生成Token并存入Redis且期限为30s~

  • 准备一个/resource接口,用来验证用户(为了方便将session验证也一起写了),逻辑为若有session则取session,若无则取headers中的token,如果都没有则返回未经授权。
    def get_resource():
            if session.get("user"):
                return jsonify({'data': 'Hello, %s!' % session.get("user")})
                token = request.headers.get("token")
                user = verify_auth_token(token)
                if isinstance(user,dict):            #判断token  若错误
                    return jsonify(verify_auth_token(token))
                    return jsonify({'data': 'Hello, %s!' % user.username})#判断token  成功 返回对象
        except  Exception as e:
            return jsonify({'error_message':'未经授权'})


  • postman测试一下哈~成功校验~,若redis不存在,token验证通过,则返回过期。(因为redis 设置的过期时间与token生成时设置的过期时间不同~)
  • 若Token在redis中过期:

  • 若Token为随意构造:


  • session存在客户端的流程图如下:
  • 我们在用session的方式来试一下,同样写一个登陆接口,用flask内置session来处理):
    def sessionLogin():
            username = request.args.get("username")
            password = request.args.get("password")
            obj = User.query.filter_by(username=username).first()
            if not obj:
                return jsonify(201,'',u'未找到该用户')
            if obj.verify_password(password):
                session["user"] = username
                return jsonify(200,f'{username}',u'登录成功')
                return jsonify(202,'',u'密码错误')
            return jsonify(203, '', u'参数错误')
  • 这次我们用浏览器请求一下~,session成功保存到Cookies中~

  • 并带着该Cookie,访问之前准备的/resource页面,验证通过。


  • session存在服务端 的流程图如下,将生成session后返回session_id,并存入redis,再次请求时,从redis获取:
  • 引入flask_session,并做如下设置,其他方法不变~:
    app.config['SECRET_KEY'] = 'ayotest'
    app.config['JSON_AS_ASCII'] = False
    app.config['SESSION_TYPE'] = 'redis'  # session类型为redis
    app.config['SESSION_PERMANENT'] = False  # 如果设置为True,则关闭浏览器session就失效。
    app.config['SESSION_USE_SIGNER'] = False  # 是否对发送到浏览器上session的cookie值进行加密
    app.config['SESSION_KEY_PREFIX'] = 'session_id:'  # 保存到session中的值的前缀
    app.config['SESSION_REDIS'] = redis.Redis(host='', password='123456',encoding='utf8')  # 用于连接redis的配置
  • 用postman请求一下,请求成功,并在cookie中生成了session id

  • 此时查看redis,成功存入~接下来我们再带着session_id去请求~

  • 构造请求,cookie中填入session_id,请求成功~


  • token类似一个令牌,无状态,用户信息都被加密到token中,服务器收到token后解密就可知道是哪个用户。可轻松做到分布式,但缺点是每次解密token需要花时间。
  • cookie类似一个载体,可承载用户信息,当使用session_id这种方式时,服务器收到cookie后解析出session_id,再去redis中查找,才能找到相应session。此缺点是存在服务端,占用服务端存储空间,分布式系统需要做共享session。


43,528 次浏览


  1. It’s a pity you don’t have a donate button! I’d definitely donate to this superb blog! I guess for now i’ll settle for book-marking and adding your RSS feed to my Google account. I look forward to brand new updates and will share this blog with my Facebook group. Talk soon!|

  2. Hey! Someone in my Myspace group shared this site with us so I came to look it over. I’m definitely enjoying the information. I’m book-marking and will be tweeting this to my followers! Great blog and outstanding design and style.|

  3. Hello there, just became alert to your blog through Google, and found that it is really informative.
    I’m gonna watch out for brussels. I’ll appreciate if you
    continue this in future. Numerous people will
    be benefited from your writing. Cheers!

  4. When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time
    a comment is added I get three emails with the same comment.

    Is there any way you can remove me from that service?
    Bless you!

  5. I’ve learn a few just right stuff here. Definitely value bookmarking for revisiting.
    I wonder how much effort you put to make the sort of excellent
    informative site.

  6. Woah! I’m really enjoying the template/theme of this website.
    It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between user friendliness and appearance.
    I must say you’ve done a superb job with this. In addition, the blog
    loads very quick for me on Firefox. Superb Blog!

  7. An outstanding share! I have just forwarded this onto
    a coworker who has been doing a little homework on this.
    And he actually ordered me dinner simply because I stumbled
    upon it for him… lol. So let me reword this…. Thanks
    for the meal!! But yeah, thanks for spending some time to discuss this issue here
    on your website.

  8. Знаете ли вы?
    Копенгагенский собор пришлось выстроить заново после визита англичан в 1807 году.
    Американская энциклопедия включила в себя десятки статей о вымышленных людях, якобы связанных с Латинской Америкой.
    Канадский солдат в одиночку освободил от немцев нидерландский город.
    После 50 черепно-мозговых травм регбист завершил карьеру, опасаясь получить синдром деменции.
    Водитель ледового комбайна стал звездой единственного матча НХЛ, в котором принял участие.


  9. Attractive component of content. I simply stumbled upon your weblog and
    in accession capital to claim that I acquire actually enjoyed account your weblog posts.
    Any way I will be subscribing to your augment or even I success you get
    right of entry to constantly rapidly.

  10. I was wondering if you ever considered changing the layout of
    your site? Its very well written; I love what youve got to say.
    But maybe you could a little more in the way of content
    so people could connect with it better. Youve got
    an awful lot of text for only having one or 2 images.
    Maybe you could space it out better?

  11. This design is steller! You definitely know
    how to keep a reader amused. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!)
    Excellent job. I really loved what you had to say, and
    more than that, how you presented it. Too cool!

  12. Greetings from California! I’m bored to tears at work so I decided to
    check out your site on my iphone during lunch break.
    I really like the info you provide here and can’t wait to
    take a look when I get home. I’m surprised at how
    fast your blog loaded on my phone .. I’m not even using WIFI, just 3G ..
    Anyways, superb site!

  13. Sorry for off-topic, I am thinking about building an instructive internet site for pupils. Will possibly start with submitting interesting information just like”Thirty-five percent of the people who use personal ads for dating are already married.”Please let me know if you know where I can find some related information like right here


  14. obviously like your website but you need to take a look
    at the spelling on quite a few of your posts.
    Several of them are rife with spelling problems and I find it very
    troublesome to inform the truth then again I’ll surely come back again.

  15. Hmm it looks like your blog ate my first comment (it was extremely long) so I guess I’ll
    just sum it up what I submitted and say, I’m thoroughly enjoying your blog.
    I as well am an aspiring blog writer but I’m still new to everything.
    Do you have any tips for novice blog writers? I’d definitely appreciate it.

  16. Does your site have a contact page? I’m having trouble locating it but, I’d like
    to send you an email. I’ve got some recommendations for your blog you might be interested in hearing.
    Either way, great blog and I look forward to seeing it grow over

  17. Thank you a lot for sharing this with all folks you actually recognize what you’re speaking approximately!
    Bookmarked. Kindly also consult with my web site =).
    We will have a hyperlink alternate arrangement between us

  18. Hi I am so delighted I found your web site, I really found you
    by mistake, while I was browsing on Askjeeve for something else, Nonetheless I am
    here now and would just like to say thank you for a incredible post and a all round thrilling blog (I also love
    the theme/design), I don’t have time to go through it all
    at the moment but I have saved it and also added in your RSS feeds, so
    when I have time I will be back to read much more, Please do keep up
    the excellent jo. adreamoftrains website hosting companies

  19. Do you have a spam issue on this website; I also am a blogger, and I was wanting to
    know your situation; many of us have developed some nice practices and
    we are looking to trade solutions with other folks, please shoot me an email if interested.

  20. I’m extremely impressed with your writing talents and also
    with the structure on your weblog. Is that this a paid subject or did you modify it your self?
    Anyway keep up the excellent quality writing, it’s
    uncommon to look a great weblog like this one these days..

  21. Fantastic website you have here but I was wondering if
    you knew of any discussion boards that cover the same topics talked
    about in this article? I’d really like to be a part of community where I can get responses from other knowledgeable people that share the same interest.
    If you have any suggestions, please let me know. Many thanks!

  22. Have you ever thought about adding a little bit more than just your articles?

    I mean, what you say is important and everything.
    But think about if you added some great visuals or video clips to give your posts more, “pop”!
    Your content is excellent but with images and clips,
    this blog could certainly be one of the greatest in its
    field. Superb blog!

  23. I was more than happy to find this page. I need to to thank you for
    ones time for this particularly wonderful read!!
    I definitely enjoyed every bit of it and I have you saved
    as a favorite to see new information on your web site.

  24. Polymorphic epitope,РІ Called thyroid cialis come by online uk my letterboxd shuts I havenРІt shunted a urology reversible in nigh a week and thats because I receive been enchanting aspirin ground contributes and be suffering with been associated a raffle but you be compelled what I specified be suffering with been receiving. casino game online casino usa real money

  25. I’m curious to find out what blog system you are using? I’m having some minor security issues with my latest site and I would like to
    find something more safe. Do you have any solutions?

  26. I believe that is one of the most significant information for me.
    And i am satisfied studying your article. However want to
    statement on few general things, The website taste is perfect, the articles is in reality excellent : D.
    Excellent task, cheers

  27. Having read this I thought it was very informative. I appreciate you
    taking the time and effort to put this informative article together.
    I once again find myself personally spending
    a lot of time both reading and commenting. But so what, it was still worthwhile!

  28. Hello, Neat post. There’s a problem with your site in internet explorer, would test this?
    IE still is the market chief and a good component of other folks will omit your great
    writing because of this problem.

  29. I just could not go away your web site before suggesting that I actually loved
    the standard info an individual provide in your guests?
    Is going to be back incessantly to investigate cross-check new posts

  30. Magnificent beat ! I wish to apprentice whilst you amend your site, how can i subscribe for a weblog website?
    The account aided me a applicable deal. I were tiny bit acquainted
    of this your broadcast offered bright clear concept

  31. Write more, thats all I have to say. Literally,
    it seems as though you relied on the video
    to make your point. You clearly know what youre talking about, why waste your
    intelligence on just posting videos to your weblog when you could be giving us something informative to read?

  32. [url=]cost for strattera[/url] [url=]chloroquine 1mg[/url] [url=]zofran online[/url] [url=]canadian pharmacy ampicillin[/url] [url=]seroquel 1200 mg daily[/url]

  33. Do you mind if I quote a few of your articles as long as I provide credit and
    sources back to your site? My blog is in the very same niche as yours and my visitors would
    truly benefit from some of the information you present here.
    Please let me know if this ok with you. Appreciate it!

  34. I like to get my inspiration from really meaningful phrases said by truly great people like “The brave man is he who overcomes not only his enemies but his pleasures”, do you know where I can find thematic compiltaions of those?

  35. Have you ever thought about writing an e-book or guest authoring on other blogs?
    I have a blog based on the same subjects you discuss and would really like to have you share some stories/information. I know my readers
    would value your work. If you’re even remotely interested,
    feel free to shoot me an e mail.

  36. Hey there just wanted to give you a quick heads
    up. The text in your content seem to be running off the screen in Opera.
    I’m not sure if this is a format issue or something to do with internet browser compatibility but I figured
    I’d post to let you know. The design look great though!
    Hope you get the problem fixed soon. Many thanks

  37. It’s a pity you don’t have a donate button! I’d most certainly
    donate to this fantastic blog! I guess for now i’ll settle for bookmarking and
    adding your RSS feed to my Google account.
    I look forward to fresh updates and will share this website with my Facebook
    group. Talk soon!

  38. ISM Phototake 3) Watney Ninth Phototake, Canada online pharmacy Phototake, Biophoto Siblings Adjunct Treatment, Inc, Under Rheumatoid Lupus LLC 4) Bennett Hundred Prison Situations, Inc 5) Ephemeral Atrial Activation LLC 6) Stockbyte 7) Bubonic Resection Grade LLC 8) Composure With and May Go payment WebMD 9) Gallop WebbWebMD 10) Shoot Resorption It LLC 11) Katie Judge and May Exhibit after WebMD 12) Phototake 13) MedioimagesPhotodisc 14) Sequestrum 15) Dr. generic viagra cost buy viagra online cheap

  39. Write more, thats all I have to say. Literally, it seems as though you relied on the video
    to make your point. You definitely know what youre talking about, why throw away your intelligence on just posting videos to your weblog
    when you could be giving us something informative to read?

  40. I’d like to thank you for the efforts you’ve put in penning this
    site. I am hoping to check out the same high-grade blog
    posts from you later on as well. In fact, your creative
    writing abilities has inspired me to get my own website now

  41. Interesting blog! Is your theme custom made or did you download it from somewhere?
    A design like yours with a few simple adjustements
    would really make my blog jump out. Please let me know where you got your theme.

    With thanks

  42. Nice post. I was checking continuously this blog
    and I am impressed! Very useful info specially the last part :
    ) I care for such info a lot. I was seeking this particular information for a long time.
    Thank you and good luck.

  43. [url=]50 mg lopressor[/url] [url=]diclofenac 75mg tab[/url] [url=]dipyridamole brand[/url] [url=]where to buy zofran[/url] [url=]ampicillin drug[/url] [url=]cost of lisinopril 30 mg[/url] [url=]arimidex 0.5 mg[/url]

  44. Do you have a spam problem on this site; I also am a blogger,
    and I was wondering your situation; many of us have created some nice practices and
    we are looking to trade methods with others, be sure to shoot me an e-mail if interested.

  45. Please let me know if you’re looking for a article writer for your site.
    You have some really good articles and I feel I
    would be a good asset. If you ever want to
    take some of the load off, I’d really like
    to write some material for your blog in exchange for a link
    back to mine. Please shoot me an e-mail if interested.

  46. naturally like your website however you have to take a look at the spelling
    on quite a few of your posts. A number of them are rife
    with spelling problems and I find it very troublesome to
    inform the reality on the other hand I’ll certainly come again again.

  47. I simply couldn’t go away your web site before suggesting
    that I actually loved the standard information a person provide for your guests?

    Is going to be back steadily in order to investigate cross-check new posts

  48. Right here is the right webpage for anyone who hopes to find out about this topic.
    You realize so much its almost tough to argue with you (not that I personally will need to…HaHa).
    You certainly put a brand new spin on a topic which has been written about for decades.
    Excellent stuff, just great!

  49. You are so interesting! I don’t believe I’ve truly read a single thing like this before.
    So great to find somebody with genuine thoughts on this subject.
    Really.. many thanks for starting this up. This site is one thing that
    is needed on the internet, someone with some originality!

  50. It’s appropriate time to make some plans for the future
    and it’s time to be happy. I have learn this publish and if I may I desire to
    suggest you some fascinating things or advice. Perhaps you
    can write next articles relating to this article.
    I wish to learn more things approximately it!

  51. [url=]how much is lisinopril 10 mg[/url] [url=]sildalis 120 mg order canadian pharmacy[/url] [url=]where can i buy albenza[/url] [url=]clonidine discount[/url]

  52. Hey I know this is off topic but I was wondering if you knew of
    any widgets I could add to my blog that automatically tweet my newest twitter updates.
    I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this.
    Please let me know if you run into anything.
    I truly enjoy reading your blog and I look forward to your new updates.

  53. Hello there! Do you know if they make any plugins to assist with SEO?
    I’m trying to get my blog to rank for some targeted keywords but
    I’m not seeing very good results. If you know of any please
    share. Appreciate it!

  54. Hello There. I found your blog using msn. This is a very well written article.
    I’ll be sure to bookmark it and come back to read more of your useful information. Thanks for the post.
    I’ll definitely comeback.

  55. After exploring a number of the blog articles on your blog, I honestly appreciate your way of blogging.
    I book-marked it to my bookmark site list and will be checking back
    soon. Take a look at my web site too and let
    me know how you feel.

  56. Hi! This post could not be written any better!
    Reading this post reminds me of my old room mate! He always kept chatting
    about this. I will forward this page to him. Fairly certain he will have a
    good read. Many thanks for sharing!

  57. [url=]bactrim ds online[/url] [url=]lisinopril 5 mg tablet[/url] [url=]medrol 16 mg generic[/url] [url=]tetracyline[/url] [url=]ciprofloxacin 500mg[/url] [url=]toradol cost[/url] [url=]buy gabapentin 800[/url] [url=]sildalis 120 mg order canadian pharmacy[/url] [url=]albenza mexico[/url] [url=]arimidex tablets in india[/url] [url=]viagra soft 50mg[/url] [url=]how much is seroquel 100mg[/url] [url=]cost of anafranil 75 mg[/url] [url=]finpecia 1 mg[/url] [url=]lipitor prices australia[/url] [url=]dipyridamole brand name uk[/url] [url=]flagyl 400[/url] [url=]best online tadalafil[/url] [url=]buy avana 50 mg[/url] [url=]avodart india price[/url]

  58. Всем привет, хочу порекомендовать вам хороший сайт о Форексе
    С недавних пор так называемые «консультационные центры», которые аферисты из ФорексШарм расплодили по всей стране, стали активно рекламировать доселе неизвестного «инновационного брокера» ФорексШарм ( ). Посмотрим на эту контору повнимательней. Приведенная на сайте ФорексШарм юридическая информация крайне скудная:

    ФорексШарм — брокерская компания родом из Шотландии
    Одна из главных черт национального шотландского характера — осмотрительность и бережливость. Этот народ имеет прагматичную, практическую жилку и привык рационально использовать финансовые ресурсы.

    При этом ФорексШарм, работающий под брендом ФорексШарм, зарегистрирован в офшоре, юридический адрес First Floor, First St. Vincent Bank Building, James Street, Kingstown, St. Vincent and the Grenadines. Какое отношение офшорная шарага, которой без сомнения является ФорексШарм, имеет к Шотландии, аферисты объяснить затруднились.

    Простой поиск в гугле показывает, что юридический адрес полностью совпадает с такими же офшорными помойками как ФорексШарм. Обе конторы являются лохотронами, связаны между собой и неоднократно становились объектами интереса правоохранительных органов в различных странах. Владелец ФорексШарм господин ФорексШарм в настоящее время находится в федеральном розыске по подозрению в мошенничестве в особо крупном размере. ФорексШарм фактически прекратил деятельность на территории СНГ, в России и Белоруссии у аферистов из ТелеТрейд была отозвана лицензия на право осуществления дилерской деятельности.

    ФорексШарм также неоднократно был замечен в обмане клиентов и необоснованных отказах в выплате денег. В прошлом году «институт трейдинга и инвестиций Феникс», поставлявший жертв мошенникам из ФорексШарм , стал фигурантом уголовного дела .

    Информация с сайта ФорексШарм:

    После более чем десяти лет работы на рынке форекс мы пришли к выводу, что хотим создать современную и удобную консалтинговую и аналитическую компанию, которая бы понимала нужды трейдеров и могла предложить лучшие условия для ведения действительно комфортной торговли.

    При этом сайт ФорексШарм с якобы десяти летним стажем зарегистрирован всего два года назад, имеет крайне низкие показатели по «авторитетности» и по сути является дешевым шаблонным ресурсом. Компания ФорексШарм была зарегистрирована в мае 2017 года, ни о каком десятилетнем стаже работы речи быть не может. В сети интернет упоминаний об этом «инвестиционном брокере» практически нет. Причина проста: мошенники решили использовать ФорексШарм совсем недавно и банально не успели распиарить эту никому не известную контору.

    Особо стоит отметить, что ФорексШарм не имеет ни одной лицензии, у этого офшорного лохотрона нет никаких прав на оказание услуг ни на территории Российской Федерации, ни на территории ЕС.

    В мессенджере ФорексШарм активно пиарит аналитические услуги через телеграм-бота. Можно не сомневаться, что итог торговли по сигналам аферистов будет закономерный и печальный. Заработать, доверяя деньги мошенникам, невозможно.


    ФорексШарм, без сомнения, является мошенническим брокером, непосредственно связанным с аферистами из ФорексШарм. Если у вас есть желание поддержать мошенников материально, вы можете отправить деньги в эту сомнительную контору. В остальных случаях рекомендуем воздерживаться от любых инвестиций в этого псевдоброкера.
    Брокер предоставляет трейдерам возможность работы на международном валютном рынке. Современная компания предлагает своим клиентам лучшие условия для ведения комфортной торговли. Сплочённая команда опытных трейдеров, аналитиков, экспертов, разработчиков маркетологов и менеджеров делает всё для своих клиентов.

    В распоряжении трейдеров выбор активов среди валют, металлов, сырья, акций, индексов и криптовалюты. Каждый клиент может открыть торговый счет, подходящий под личные цели и финансовые возможности. Кредитное плечо зависит от выбранного актива от 1:1 до 1:500.

    Множество аналитических материалов делает торговлю с ФорексШарм простой и комфортной. Клиенты могут оценить качество авторской аналитики, экономический календарь, представленный на сайте, новости и прогнозы от Trading Central. У каждого трейдера есть возможность зарабатывать с максимальной вероятность, используя инвестиционные идеи, основанные на реальных событиях.

    Преимущества брокера ФорексШарм:

    1. Высокая точность аналитики.
    2. Отличные торговые условия.
    3. Возможность обучения для трейдеров с различным опытом.
    4. Отсутствие рисков и гарантия безопасности средств.
    5. Удобный вводи вывод средств.
    Брокер предлагает 4 варианта обучения для каждого трейдера, исходя из его опыта и имеющихся знаний до этого:

    1. Базовый курс: «Основы анализа финансовых рынков».
    2. Продвинутый курс: «Технический и фундаментальный анализы финансовых рынков».
    3. Профессиональный курс: «Построение торговых систем и тактик».
    4. Экспертный курс: «Мастер-класс».
    Приятные акции и бонусы помогают начинающим трейдерам освоиться на рынке и не потерять сразу же весь депозит.

    Так же есть возможность открыть демо-счет и тренироваться на нем, пока трейдер не почувствует в себе уверенность.

    Связь со службой поддержки осуществляется с помощью телефона или электронной почты. Сотрудники компании владеют всеми популярными языками мира, поэтому каждый трейдер будет иметь возможность решить свою проблему.