Use the Django framework to build a game website.

Source: Internet
Author: User

Use the Django framework to build a game website.

Click the open link for the complete Project Link


In the previous article, we used Javascript and Html5 to implement a fl game. In this article, we hope to implement a game website based on it to enable user registration and login, game score records, and ranking display, weibo sharing and other functions.





Final effect:


2. website construction and server Construction

2.1 Overall website Composition

I use the django framework for website construction.

2.1.1 Database Design

User:

Field

Type

Null

Key

Default

Description

Name

Varchar (50)

No

Primary

 

User ID

Password

Varchar (50)

No

 

 

User Password

BestScore

Integer

No

 

0

Highest user score

Name

Varchar (20)

No

 

 

Legal Representative name

Corresponding Models;


class Player(models.Model):    name = models.CharField(max_length=50, primary_key =True)    password = models.CharField(max_length=50)    bestScore = models.PositiveIntegerField()    def __unicode__(self):        return u'%s %s %s %s %s' % (self.name, self.password, self.weibo, self.weboPw, self.bestScore)

2.1.2 Website Design

Website architecture diagram:

URL settings

 (r'^$', views.login),    (r'^index/$', views.index),    (r'^ballgame/$', views.game),    (r'^signup/$', views.signup),    (r'^signresult/$', views.signResult),    (r'^login/$', views.loginResult),    (r'^storeScore/(?P<score>[\d]*)/$', views.storeScore),    (r'^logout/$', views.logout),        (r'^site_media/(?P<path>.*)$','django.views.static.serve',{'document_root': settings.STATIC_PATH}),


Corresponding Views:

Key Point: logon control. After logon, a session is written to the request, indicating that the session has been logged on. When each URL request is received, the session is judged in views. If this information is not found in the session, the logon page is returned. Logout deletes the session information in the request.


// Login result def loginResult (request): if request. method = "POST": username = request. POST ["username"] try: user = Player. objects. get (name = username) response t ObjectDoesNotExist: return render_to_response ("login.html") passwd = request. POST ["password"] if passwd! = User. password: return HttpResponseRedirect ("/") request. session ['user _ id'] = user. name; return HttpResponseRedirect ("/index/") // logon page def login (request): if "user_id" in request. session: return HttpResponseRedirect ("/index/") else: return render_to_response('login.html ') // register the page def signup (request): return comment') // logout def logout (request ): try: del request. session ['user _ id'] failed t KeyError: pass return render_to_response('login.html ') // def index (request) on the index page ): // use the session control in the request to log on to if "user_id" in request. session: res = Player. objects. order_by ('-bestScore') [0: 9] user = Player. objects. get (name = request. session ["user_id"]) score = user. bestScore count = 1 ares = Player. objects. order_by ('-bestScore') for p in ares: if p. name = request. session ["user_id"]: break else: count = count + 1 return render_to_response('index.html ', {"username": request. session ["user_id"], "bestPlayer": res, "score": score, "rank": count}) else: return render_to_response('login.html ') // game page def game (request): if "user_id" in request. session: return render_to_response('ballGame.html ', {"username": request. session ["user_id"]}) else: return HttpResponseRedirect ("") // The registration result page def signResult (request): if request. method = "POST": username = request. POST ["username"] try: existed = Player. objects. get (name = username) Does T ObjectDoesNotExist: passwd = request. POST ["password"] p = Player (name = username, password = passwd, bestScore = 1) p. save () return render_to_response ("signSucceed.html") return HttpResponseRedirect ("/signup/") // save score def storeScore (request, score): if 'user _ id' in request. session: userid = request. session ['user _ id'] try: user = Player. objects. get (name = userid) doesn t ObjectDoesNotExist: return HttpResponseRedirect ("") oldScore = user. bestScore; print type (oldScore) print type (score) score = long (score) if score> oldScore: print "yes" bestScore = score user. bestScore = score user. save () else: bestScore = oldScore return render_to_response ("score.html", {"username": user. name, "thisscore": score, "bestScore": bestScore}) else: return HttpResponseRedirect ("")

 

2.1.3 server Construction

This website uses the Apache server, which by default does not support python. Therefore, external modules need to be loaded. Module_wsgi is used here.


Configuration steps:

A. Download the compiled module_wsgi.so from the website and place it in the apache installation directory/modules folder. Add the following content to the apache installation directory/conf/httpd. conf file that has been loaded into this module.

LoadModule wsgi_module modules/mod_wsgi.soWSGIScriptAlias/"F:/danjo/game/django. wsgi" // set/url corresponding file. Alias/site_media F:/danjo/game/static // set the directory corresponding to/site_media url. This website places all static content loaded in this folder. <Directory/> Options FollowSymLinks AllowOverride None Order deny, allow Deny from allow here sets the access permission for/root Directory </Directory> <Directory "F: /danjo/game "> // This Directory is the Directory of the django project Order deny, allow from all </Directory>



Add files to the django project directory. Django. wsgi.

import osimport sysimport django.core.handlers.wsgisys.path.append(r'F:/danjo/game')os.environ['DJANGO_SETTINGS_MODULE'] = 'game.settings'application = django.core.handlers.wsgi.WSGIHandler()


In this way, you can access the website built by our django framework in apache.

 

 

3. Implementation of Weibo Functions

The Weibo sharing function requires the Weibo API. The javascript API is used here. To use APIs, you must register applications on the Weibo Open Platform and indicate the website ownership. All websites that need to be able to log on to the Internet. So you need to register a domain name. Here I choose to use a dynamic Domain Name Server with a peanut shell. And uses its free Domain Name kkopq.xicp.net.

After completing the preceding steps, it is easy to implement Weibo sharing. Add the following content to the page for Weibo:

<Script src = "http://tjs.sjs.sinajs.cn/open/api/js/wb.js? Appkey = 2556191936 "type =" text/javascript "charset =" UTF-8 "> </script> // This is the Library of Weibo api. Note that you need to add the registered app and obtain the appkey.

 

 

Define share button:

<P> <button class = "btn-success btn-hg" style = "width: 200px; height: 50px "type =" button "id =" wb_publish "> share </wb: button> </p> <script> WB2.anyWhere (function (W) {W. widget. publish ({id: 'wb _ publish ', default_text:' I have gotten {score} points in the KKball game! Come to play with me at kkopq.xicp.net! [Ye] [ye] [ye] '}) ;}); </script>


4. html UI design.

I used the Flat UI framework for Web UI.

 



Use the django framework for python website development

In my opinion, the front-end page collects the URLs to be accessed and writes them to the database. A process starts in the background, reads the URLs from the database regularly, and sends http get requests to the URLs.
 
How to build a website

Website construction is divided into the following eight steps: 1. Apply for a domain name (Domain Name filing); 2. Apply for a space; 3. Locate a website; 4. Analyze website functions and requirements (website Planning) 5. Website style design; 6. website code production; 7. Test websites; 8. Upload websites through FTP; 9. website maintenance
Website construction includes
Website construction includes Website planning, webpage design, Website Functions, website content sorting, website promotion, website evaluation, website operation, and overall website optimization, the purpose of website construction is to conduct online marketing and e-commerce through websites. The network marketing consultant first proposes a low-cost network marketing plan for website construction. By gaining insight into the network marketing strategy of the target customer group of the project, the company can trigger and leverage the interactions between enterprises and netizens, as well as between netizens and netizens, so that enterprises can surpass competitors with the minimum marketing investment, get more efficient market return marketing Website planning website pre-planning as the starting point of network marketing, the rigor and practicality of planning will directly affect the realization of enterprise network marketing goals. Website builders are guided by customer needs and network marketing, and assist different types of enterprises based on their professional planning experience to meet the strategic objectives and tactical requirements of enterprises at different stages, develop phased website plans for enterprises. Based on years of website construction and development experience, the information port for marketing website construction and implementation builds a good information communication bridge between enterprises and their external systems. Based on the preliminary plan, establish website information organization with Website user experience as the core, customize website visual design, customize website functions, and develop and efficiently integrate website systems. In addition to rigorous Website planning and perfect website construction, whether a website promotion plan can meet the expected marketing business objectives depends on the formulation and implementation of a well-planned website promotion plan. Relying on its many years of experience in website promotion and search engine optimization, we help customers make full use of the advantages of the Internet and combine various website promotion strategies in order to gain more business opportunities.
Edit the benefits of professional website construction in this section
After all, enterprise websites are different from professional ICP or portal websites and cannot be small and complete. Each enterprise has its own specific products/services. The content of the website should be set around the core business of the enterprise. Enterprise websites should not be just a decoration, but websites are the most useful marketing tools. Of course, the marketing function of a website can play a role only when the website can meet the user's needs. Use website construction
What information does the user need?
Website planning
This problem is the first consideration for Website planning. First, you must analyze the possible visitors and then design relevant content in a targeted manner. Generally, there are several types of visitors to an enterprise website: direct users, dealers, equipment and raw material suppliers, competitors, etc. The first two types of visitors are existing and potential users of the company, and they are also the target of website content. As for suppliers, except for the comprehensive e-commerce websites with B to B functions, most enterprise websites that focus on information publishing seldom take into account. Therefore, these websites are not the key content of general enterprise websites. As for competitors, the purpose of the visit is nothing more than understanding the new trends of your company, or the level of website design, whether there is something worth learning from, when releasing relevant content, we should give appropriate "defense", rather than let competitors get back to the market.
Content should be the focus of the website
Since the company's existing users and potential users are the focus of the website, it is necessary to carefully analyze what information they need. Taking a TV manufacturer as an example, a user/potential user can access a company's website for several purposes: check what new products are available, compare the performance and prices of products of different specifications, compare with similar products of other brands, query local sellers and warranty addresses, etc. If you can order them online, users also naturally want to know the relevant information, such as the ordering method, payment method, delivery time and cost, and the return and exchange product policy. Therefore, the content should be the focus of the website. It seems that we can't understand the truth. However, many websites often encounter the "problem" Phenomenon in content design. Even in the United States, where e-commerce is already relatively developed, the unreasonable design of Enterprise websites is also very obvious. In China, maybe it is... the rest of the article>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.